From 7580f45ea48a7b5f537a24d99c2de56ffefa5e1a Mon Sep 17 00:00:00 2001 From: Wenhua Zhang Date: Thu, 4 Jun 2020 17:11:33 +0800 Subject: [PATCH 01/60] feat: reopen shielded transaction releated codes, and update the determine func in grpc --- .../org/tron/core/utils/ProposalUtil.java | 83 ++++++++++--------- .../java/org/tron/common/utils/DBConfig.java | 6 +- .../core/store/DynamicPropertiesStore.java | 3 +- .../src/main/java/org/tron/core/Constant.java | 4 +- .../src/main/java/org/tron/core/Wallet.java | 32 +++---- .../java/org/tron/core/config/args/Args.java | 16 ++-- .../tron/core/consensus/ProposalService.java | 32 +++---- .../org/tron/core/services/RpcApiService.java | 20 ++--- .../services/http/FullNodeHttpApiService.java | 26 +++--- .../solidity/SolidityNodeHttpApiService.java | 20 ++--- .../solidity/HttpApiOnSolidityService.java | 21 +++-- .../src/main/resources/config-localtest.conf | 5 ++ 12 files changed, 138 insertions(+), 130 deletions(-) diff --git a/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java b/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java index 7bc2616118a..c34293ddafe 100644 --- a/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java +++ b/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java @@ -250,42 +250,47 @@ public static void validator(DynamicPropertiesStore dynamicPropertiesStore, Fork } break; } -// case ALLOW_SHIELDED_TRANSACTION: { -// if (!forkUtils.pass(ForkBlockVersionEnum.VERSION_4_0)) { -// throw new ContractValidateException( -// "Bad chain parameter id [ALLOW_SHIELDED_TRANSACTION]"); -// } -// if (value != 1) { -// throw new ContractValidateException( -// "This value[ALLOW_SHIELDED_TRANSACTION] is only allowed to be 1"); -// } -// break; -// } -// case SHIELDED_TRANSACTION_FEE: { -// if (!forkUtils.pass(ForkBlockVersionEnum.VERSION_4_0)) { -// throw new ContractValidateException("Bad chain parameter id [SHIELD_TRANSACTION_FEE]"); -// } -// if (!dynamicPropertiesStore.supportShieldedTransaction()) { -// throw new ContractValidateException( -// "Shielded Transaction is not activated, can not set Shielded Transaction fee"); -// } -// if (value < 0 || value > 10_000_000_000L) { -// throw new ContractValidateException( -// "Bad SHIELD_TRANSACTION_FEE parameter value, valid range is [0,10_000_000_000L]"); -// } -// break; -// } -// case SHIELDED_TRANSACTION_CREATE_ACCOUNT_FEE: { -// if (!forkUtils.pass(ForkBlockVersionEnum.VERSION_4_0)) { -// throw new ContractValidateException("Bad chain parameter id [SHIELDED_TRANSACTION_CREATE_ACCOUNT_FEE]"); -// } -// if (value < 0 || value > 10_000_000_000L) { -// throw new ContractValidateException( -// "Bad SHIELDED_TRANSACTION_CREATE_ACCOUNT_FEE parameter value,valid range is [0,10_000_000_000L]"); -// } -// break; -// } - case FORBID_TRANSFER_TO_CONTRACT: { + case ALLOW_SHIELDED_TRANSACTION: { + if (!forkUtils.pass(ForkBlockVersionEnum.VERSION_4_0)) { + throw new ContractValidateException( + "Bad chain parameter id [ALLOW_SHIELDED_TRANSACTION]"); + } + if (value != 1) { + throw new ContractValidateException( + "This value[ALLOW_SHIELDED_TRANSACTION] is only allowed to be 1"); + } + break; + } + case SHIELDED_TRANSACTION_FEE: { + if (!forkUtils.pass(ForkBlockVersionEnum.VERSION_4_0)) { + throw new ContractValidateException("Bad chain parameter id [SHIELD_TRANSACTION_FEE]"); + } + if (!dynamicPropertiesStore.supportShieldedTransaction()) { + throw new ContractValidateException( + "Shielded Transaction is not activated, can not set SHIELD_TRANSACTION_FEE"); + } + if (value < 0 || value > 10_000_000_000L) { + throw new ContractValidateException( + "Bad SHIELD_TRANSACTION_FEE parameter value, valid range is [0,10_000_000_000L]"); + } + break; + } + case SHIELDED_TRANSACTION_CREATE_ACCOUNT_FEE: { + if (!forkUtils.pass(ForkBlockVersionEnum.VERSION_4_0)) { + throw new ContractValidateException( + "Bad chain parameter id [SHIELDED_TRANSACTION_CREATE_ACCOUNT_FEE]"); + } + if (!dynamicPropertiesStore.supportShieldedTransaction()) { + throw new ContractValidateException( + "Shielded Transaction is not activated, can not set SHIELDED_TRANSACTION_CREATE_ACCOUNT_FEE"); + } + if (value < 0 || value > 10_000_000_000L) { + throw new ContractValidateException( + "Bad SHIELDED_TRANSACTION_CREATE_ACCOUNT_FEE parameter value, valid range is [0,10_000_000_000L]"); + } + break; + } + case FORBID_TRANSFER_TO_CONTRACT: { if (!forkUtils.pass(ForkBlockVersionEnum.VERSION_3_6_6)) { throw new ContractValidateException(BAD_PARAM_ID); @@ -345,14 +350,14 @@ public enum ProposalType { ALLOW_PROTO_FILTER_NUM(24), // 1, 24 ALLOW_ACCOUNT_STATE_ROOT(25), // 1, 25 ALLOW_TVM_CONSTANTINOPLE(26), // 1, 26 -// ALLOW_SHIELDED_TRANSACTION(27), // 27 -// SHIELDED_TRANSACTION_FEE(28), // 28 + ALLOW_SHIELDED_TRANSACTION(27), // 27 + SHIELDED_TRANSACTION_FEE(28), // 28 ADAPTIVE_RESOURCE_LIMIT_MULTIPLIER(29), // 1000, 29 ALLOW_CHANGE_DELEGATION(30), //1, 30 WITNESS_127_PAY_PER_BLOCK(31), //drop, 31 ALLOW_TVM_SOLIDITY_059(32), // 1, 32 ADAPTIVE_RESOURCE_LIMIT_TARGET_RATIO(33), // 10, 33 - // SHIELDED_TRANSACTION_CREATE_ACCOUNT_FEE(34); // 34 + SHIELDED_TRANSACTION_CREATE_ACCOUNT_FEE(34), // 34 FORBID_TRANSFER_TO_CONTRACT(35), // 1, 35 ALLOW_SHIELDED_TRC20_TRANSACTION(39); // 1, 39 diff --git a/chainbase/src/main/java/org/tron/common/utils/DBConfig.java b/chainbase/src/main/java/org/tron/common/utils/DBConfig.java index 4560cb74dc1..f4eaddb36e5 100644 --- a/chainbase/src/main/java/org/tron/common/utils/DBConfig.java +++ b/chainbase/src/main/java/org/tron/common/utils/DBConfig.java @@ -74,9 +74,9 @@ public class DBConfig { @Getter @Setter private static long allowCreationOfContracts; //committee parameter -// @Getter -// @Setter -// private static long allowShieldedTransaction; //committee parameter + @Getter + @Setter + private static long allowShieldedTransaction; //committee parameter @Getter @Setter private static long allowShieldedTRC20Transaction; diff --git a/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java b/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java index c88bc8ab320..71ed26c7901 100644 --- a/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java +++ b/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java @@ -537,8 +537,7 @@ private DynamicPropertiesStore(@Value("properties") String dbName) { try { this.getAllowShieldedTransaction(); } catch (IllegalArgumentException e) { -// this.saveAllowShieldedTransaction(DBConfig.getAllowShieldedTransaction()); - this.saveAllowShieldedTransaction(0L); + this.saveAllowShieldedTransaction(DBConfig.getAllowShieldedTransaction()); } try { diff --git a/common/src/main/java/org/tron/core/Constant.java b/common/src/main/java/org/tron/core/Constant.java index 2d77c6010ef..67aa39137ca 100644 --- a/common/src/main/java/org/tron/core/Constant.java +++ b/common/src/main/java/org/tron/core/Constant.java @@ -157,7 +157,7 @@ public class Constant { public static final String STORAGE_NEEDTO_UPDATE_ASSET = "storage.needToUpdateAsset"; - public static final String TRX_REFERENCE_BLOCK = "trx.reference.block"; + public static final String TRX_REFERENCE_BLOCK = "trx.reference.block"; public static final String TRX_EXPIRATION_TIME_IN_MILLIS_SECONDS = "trx.expiration.timeInMilliseconds"; @@ -169,7 +169,7 @@ public class Constant { public static final String VM_SAVE_INTERNAL_TX = "vm.saveInternalTx"; -// public static final String COMMITTEE_ALLOW_SHIELDED_TRANSACTION = "committee.allowShieldedTransaction"; + public static final String COMMITTEE_ALLOW_SHIELDED_TRANSACTION = "committee.allowShieldedTransaction"; public static final String COMMITTEE_ALLOW_SHIELDED_TRC20_TRANSACTION = "committee" + ".allowShieldedTRC20Transaction"; diff --git a/framework/src/main/java/org/tron/core/Wallet.java b/framework/src/main/java/org/tron/core/Wallet.java index f18a2839ed9..0c1e8177776 100755 --- a/framework/src/main/java/org/tron/core/Wallet.java +++ b/framework/src/main/java/org/tron/core/Wallet.java @@ -964,26 +964,26 @@ public Protocol.ChainParameters getChainParameters() { .build()); // ALLOW_SHIELDED_TRANSACTION - // builder.addChainParameter( - // Protocol.ChainParameters.ChainParameter.newBuilder() - // .setKey("getAllowShieldedTransaction") - // .setValue(dbManager.getDynamicPropertiesStore().getAllowShieldedTransaction()) - // .build()); + builder.addChainParameter( + Protocol.ChainParameters.ChainParameter.newBuilder() + .setKey("getAllowShieldedTransaction") + .setValue(dbManager.getDynamicPropertiesStore().getAllowShieldedTransaction()) + .build()); // SHIELDED_TRANSACTION_FEE - // builder.addChainParameter( - // Protocol.ChainParameters.ChainParameter.newBuilder() - // .setKey("getShieldedTransactionFee") - // .setValue(dbManager.getDynamicPropertiesStore().getShieldedTransactionFee()) - // .build()); + builder.addChainParameter( + Protocol.ChainParameters.ChainParameter.newBuilder() + .setKey("getShieldedTransactionFee") + .setValue(dbManager.getDynamicPropertiesStore().getShieldedTransactionFee()) + .build()); // ShieldedTransactionCreateAccountFee - // builder.addChainParameter( - // Protocol.ChainParameters.ChainParameter.newBuilder() - // .setKey("getShieldedTransactionCreateAccountFee") - // .setValue( - // dbManager.getDynamicPropertiesStore().getShieldedTransactionCreateAccountFee()) - // .build()); + builder.addChainParameter( + Protocol.ChainParameters.ChainParameter.newBuilder() + .setKey("getShieldedTransactionCreateAccountFee") + .setValue( + dbManager.getDynamicPropertiesStore().getShieldedTransactionCreateAccountFee()) + .build()); // ALLOW_SHIELDED_TRC20_TRANSACTION builder.addChainParameter( diff --git a/framework/src/main/java/org/tron/core/config/args/Args.java b/framework/src/main/java/org/tron/core/config/args/Args.java index ec9276b2e40..6c60b315b86 100644 --- a/framework/src/main/java/org/tron/core/config/args/Args.java +++ b/framework/src/main/java/org/tron/core/config/args/Args.java @@ -444,9 +444,9 @@ public class Args { @Setter private int minEffectiveConnection; -// @Getter -// @Setter -// private long allowShieldedTransaction; //committee parameter + @Getter + @Setter + private long allowShieldedTransaction; //committee parameter // full node used this parameter to close shielded transaction @Getter @@ -606,7 +606,7 @@ public static void clearParam() { INSTANCE.minTimeRatio = 0.0; INSTANCE.maxTimeRatio = 5.0; INSTANCE.longRunningTime = 10; -// INSTANCE.allowShieldedTransaction = 0; + INSTANCE.allowShieldedTransaction = 0; INSTANCE.allowShieldedTRC20Transaction = 0; INSTANCE.maxHttpConnectNumber = 50; INSTANCE.allowMultiSign = 0; @@ -1034,9 +1034,9 @@ public static void setParam(final String[] args, final String confFileName) { INSTANCE.saveInternalTx = config.hasPath(Constant.VM_SAVE_INTERNAL_TX) && config.getBoolean(Constant.VM_SAVE_INTERNAL_TX); -// INSTANCE.allowShieldedTransaction = -// config.hasPath(Constant.COMMITTEE_ALLOW_SHIELDED_TRANSACTION) ? config -// .getInt(Constant.COMMITTEE_ALLOW_SHIELDED_TRANSACTION) : 0; + INSTANCE.allowShieldedTransaction = + config.hasPath(Constant.COMMITTEE_ALLOW_SHIELDED_TRANSACTION) ? config + .getInt(Constant.COMMITTEE_ALLOW_SHIELDED_TRANSACTION) : 0; INSTANCE.allowShieldedTRC20Transaction = config.hasPath(Constant.COMMITTEE_ALLOW_SHIELDED_TRC20_TRANSACTION) ? config @@ -1514,7 +1514,7 @@ public static void initDBConfig(Args cfgArgs) { DBConfig.setLongRunningTime(cfgArgs.getLongRunningTime()); DBConfig.setChangedDelegation(cfgArgs.getChangedDelegation()); DBConfig.setActuatorSet(cfgArgs.getActuatorSet()); -// DBConfig.setECKeyCryptoEngine(cfgArgs.isECKeyCryptoEngine()); + DBConfig.setECKeyCryptoEngine(cfgArgs.isECKeyCryptoEngine()); DBConfig.setECKeyCryptoEngine(cfgArgs.isEckey()); } diff --git a/framework/src/main/java/org/tron/core/consensus/ProposalService.java b/framework/src/main/java/org/tron/core/consensus/ProposalService.java index 2464d73ea3b..4366a67b568 100644 --- a/framework/src/main/java/org/tron/core/consensus/ProposalService.java +++ b/framework/src/main/java/org/tron/core/consensus/ProposalService.java @@ -173,22 +173,22 @@ public static boolean process(Manager manager, ProposalCapsule proposalCapsule) manager.getDynamicPropertiesStore().saveWitness127PayPerBlock(entry.getValue()); break; } -// case ALLOW_SHIELDED_TRANSACTION: { -// if (manager.getDynamicPropertiesStore().getAllowShieldedTransaction() == 0) { -// manager.getDynamicPropertiesStore().saveAllowShieldedTransaction(entry.getValue()); -// manager.getDynamicPropertiesStore().addSystemContractAndSetPermission(51); -// } -// break; -// } -// case SHIELDED_TRANSACTION_FEE: { -// manager.getDynamicPropertiesStore().saveShieldedTransactionFee(entry.getValue()); -// break; -// } -// case SHIELDED_TRANSACTION_CREATE_ACCOUNT_FEE: { -// manager.getDynamicPropertiesStore() -// .saveShieldedTransactionCreateAccountFee(entry.getValue()); -// break; -// } + case ALLOW_SHIELDED_TRANSACTION: { + if (manager.getDynamicPropertiesStore().getAllowShieldedTransaction() == 0) { + manager.getDynamicPropertiesStore().saveAllowShieldedTransaction(entry.getValue()); + manager.getDynamicPropertiesStore().addSystemContractAndSetPermission(51); + } + break; + } + case SHIELDED_TRANSACTION_FEE: { + manager.getDynamicPropertiesStore().saveShieldedTransactionFee(entry.getValue()); + break; + } + case SHIELDED_TRANSACTION_CREATE_ACCOUNT_FEE: { + manager.getDynamicPropertiesStore() + .saveShieldedTransactionCreateAccountFee(entry.getValue()); + break; + } case FORBID_TRANSFER_TO_CONTRACT: { manager.getDynamicPropertiesStore().saveForbidTransferToContract(entry.getValue()); break; diff --git a/framework/src/main/java/org/tron/core/services/RpcApiService.java b/framework/src/main/java/org/tron/core/services/RpcApiService.java index 935134fab70..9ddb614a758 100755 --- a/framework/src/main/java/org/tron/core/services/RpcApiService.java +++ b/framework/src/main/java/org/tron/core/services/RpcApiService.java @@ -2039,7 +2039,7 @@ public void getNewShieldedAddress(EmptyMessage request, StreamObserver responseObserver) { try { - checkSupportShieldedTRC20Transaction(); + checkSupportShieldedTransaction(); responseObserver.onNext(wallet.getNewShieldedAddress()); } catch (Exception e) { @@ -2052,7 +2052,7 @@ public void getNewShieldedAddress(EmptyMessage request, public void getSpendingKey(EmptyMessage request, StreamObserver responseObserver) { try { - checkSupportShieldedTRC20Transaction(); + checkSupportShieldedTransaction(); responseObserver.onNext(wallet.getSpendingKey()); } catch (Exception e) { @@ -2065,7 +2065,7 @@ public void getSpendingKey(EmptyMessage request, public void getRcm(EmptyMessage request, StreamObserver responseObserver) { try { - checkSupportShieldedTRC20Transaction(); + checkSupportShieldedTransaction(); responseObserver.onNext(wallet.getRcm()); } catch (Exception e) { @@ -2080,7 +2080,7 @@ public void getExpandedSpendingKey(BytesMessage request, ByteString spendingKey = request.getValue(); try { - checkSupportShieldedTRC20Transaction(); + checkSupportShieldedTransaction(); ExpandedSpendingKeyMessage response = wallet.getExpandedSpendingKey(spendingKey); responseObserver.onNext(response); @@ -2096,7 +2096,7 @@ public void getAkFromAsk(BytesMessage request, StreamObserver resp ByteString ak = request.getValue(); try { - checkSupportShieldedTRC20Transaction(); + checkSupportShieldedTransaction(); responseObserver.onNext(wallet.getAkFromAsk(ak)); } catch (BadItemException | ZksnarkException e) { @@ -2111,7 +2111,7 @@ public void getNkFromNsk(BytesMessage request, StreamObserver resp ByteString nk = request.getValue(); try { - checkSupportShieldedTRC20Transaction(); + checkSupportShieldedTransaction(); responseObserver.onNext(wallet.getNkFromNsk(nk)); } catch (BadItemException | ZksnarkException e) { @@ -2128,7 +2128,7 @@ public void getIncomingViewingKey(ViewingKeyMessage request, ByteString nk = request.getNk(); try { - checkSupportShieldedTRC20Transaction(); + checkSupportShieldedTransaction(); responseObserver.onNext(wallet.getIncomingViewingKey(ak.toByteArray(), nk.toByteArray())); } catch (ZksnarkException e) { @@ -2142,7 +2142,7 @@ public void getIncomingViewingKey(ViewingKeyMessage request, public void getDiversifier(EmptyMessage request, StreamObserver responseObserver) { try { - checkSupportShieldedTRC20Transaction(); + checkSupportShieldedTransaction(); DiversifierMessage d = wallet.getDiversifier(); responseObserver.onNext(d); @@ -2160,7 +2160,7 @@ public void getZenPaymentAddress(IncomingViewingKeyDiversifierMessage request, DiversifierMessage d = request.getD(); try { - checkSupportShieldedTRC20Transaction(); + checkSupportShieldedTransaction(); PaymentAddressMessage saplingPaymentAddressMessage = wallet.getPaymentAddress(new IncomingViewingKey(ivk.getIvk().toByteArray()), @@ -2263,7 +2263,7 @@ public void createShieldNullifier(GrpcAPI.NfParameters request, public void createSpendAuthSig(SpendAuthSigParameters request, StreamObserver responseObserver) { try { - checkSupportShieldedTRC20Transaction(); + checkSupportShieldedTransaction(); BytesMessage spendAuthSig = wallet.createSpendAuthSig(request); responseObserver.onNext(spendAuthSig); diff --git a/framework/src/main/java/org/tron/core/services/http/FullNodeHttpApiService.java b/framework/src/main/java/org/tron/core/services/http/FullNodeHttpApiService.java index 7030f21109f..3943274f4bb 100644 --- a/framework/src/main/java/org/tron/core/services/http/FullNodeHttpApiService.java +++ b/framework/src/main/java/org/tron/core/services/http/FullNodeHttpApiService.java @@ -391,21 +391,21 @@ public void start() { context.addServlet(new ServletHolder(getDiversifierServlet), "/getdiversifier"); context.addServlet(new ServletHolder(getIncomingViewingKeyServlet), "/getincomingviewingkey"); context.addServlet(new ServletHolder(getZenPaymentAddressServlet), "/getzenpaymentaddress"); - // context.addServlet(new ServletHolder(createShieldedTransactionServlet), - // "/createshieldedtransaction"); - // context.addServlet(new ServletHolder(createShieldedTransactionWithoutSpendAuthSigServlet), - // "/createshieldedtransactionwithoutspendauthsig"); - // context.addServlet(new ServletHolder(scanNoteByIvkServlet), "/scannotebyivk"); - // context.addServlet(new ServletHolder(scanAndMarkNoteByIvkServlet), "/scanandmarknotebyivk"); - // context.addServlet(new ServletHolder(scanNoteByOvkServlet), "/scannotebyovk"); + context.addServlet(new ServletHolder(createShieldedTransactionServlet), + "/createshieldedtransaction"); + context.addServlet(new ServletHolder(createShieldedTransactionWithoutSpendAuthSigServlet), + "/createshieldedtransactionwithoutspendauthsig"); + context.addServlet(new ServletHolder(scanNoteByIvkServlet), "/scannotebyivk"); + context.addServlet(new ServletHolder(scanAndMarkNoteByIvkServlet), "/scanandmarknotebyivk"); + context.addServlet(new ServletHolder(scanNoteByOvkServlet), "/scannotebyovk"); context.addServlet(new ServletHolder(getRcmServlet), "/getrcm"); - // context.addServlet(new ServletHolder(getMerkleTreeVoucherInfoServlet), - // "/getmerkletreevoucherinfo"); - // context.addServlet(new ServletHolder(isSpendServlet), "/isspend"); + context.addServlet(new ServletHolder(getMerkleTreeVoucherInfoServlet), + "/getmerkletreevoucherinfo"); + context.addServlet(new ServletHolder(isSpendServlet), "/isspend"); context.addServlet(new ServletHolder(createSpendAuthSigServlet), "/createspendauthsig"); - // context.addServlet(new ServletHolder(createShieldNullifierServlet), "/createshieldnullifier"); - // context.addServlet(new ServletHolder(getShieldTransactionHashServlet), - // "/getshieldtransactionhash"); + context.addServlet(new ServletHolder(createShieldNullifierServlet), "/createshieldnullifier"); + context.addServlet(new ServletHolder(getShieldTransactionHashServlet), + "/getshieldtransactionhash"); // for shielded contract context .addServlet(new ServletHolder(isShieldedTRC20ContractNoteSpentServlet), diff --git a/framework/src/main/java/org/tron/core/services/http/solidity/SolidityNodeHttpApiService.java b/framework/src/main/java/org/tron/core/services/http/solidity/SolidityNodeHttpApiService.java index 48cab1f3ef1..dc1191665e4 100644 --- a/framework/src/main/java/org/tron/core/services/http/solidity/SolidityNodeHttpApiService.java +++ b/framework/src/main/java/org/tron/core/services/http/solidity/SolidityNodeHttpApiService.java @@ -174,16 +174,16 @@ public void start() { context.addServlet(new ServletHolder(getBlockByLatestNumServlet), "/walletsolidity/getblockbylatestnum"); - // context.addServlet(new ServletHolder(getMerkleTreeVoucherInfoServlet), - // "/walletsolidity/getmerkletreevoucherinfo"); - // context.addServlet(new ServletHolder(scanAndMarkNoteByIvkServlet), - // "/walletsolidity/scanandmarknotebyivk"); - // context.addServlet(new ServletHolder(scanNoteByIvkServlet), - // "/walletsolidity/scannotebyivk"); - // context.addServlet(new ServletHolder(scanNoteByOvkServlet), - // "/walletsolidity/scannotebyovk"); - // context.addServlet(new ServletHolder(isSpendServlet), - // "/walletsolidity/isspend"); + context.addServlet(new ServletHolder(getMerkleTreeVoucherInfoServlet), + "/walletsolidity/getmerkletreevoucherinfo"); + context.addServlet(new ServletHolder(scanAndMarkNoteByIvkServlet), + "/walletsolidity/scanandmarknotebyivk"); + context.addServlet(new ServletHolder(scanNoteByIvkServlet), + "/walletsolidity/scannotebyivk"); + context.addServlet(new ServletHolder(scanNoteByOvkServlet), + "/walletsolidity/scannotebyovk"); + context.addServlet(new ServletHolder(isSpendServlet), + "/walletsolidity/isspend"); context.addServlet(new ServletHolder(scanShieldedTRC20NotesbyIvkServlet), "/walletsolidity/scanshieldedtrc20notesbyivk"); diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/solidity/HttpApiOnSolidityService.java b/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/solidity/HttpApiOnSolidityService.java index 9ffa490b265..29c694dd232 100644 --- a/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/solidity/HttpApiOnSolidityService.java +++ b/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/solidity/HttpApiOnSolidityService.java @@ -171,16 +171,16 @@ public void start() { "/walletsolidity/getblockbylimitnext"); context.addServlet(new ServletHolder(getBlockByLatestNumOnSolidityServlet), "/walletsolidity/getblockbylatestnum"); - // context.addServlet(new ServletHolder(getMerkleTreeVoucherInfoOnSolidityServlet), - // "/walletsolidity/getmerkletreevoucherinfo"); - // context.addServlet(new ServletHolder(scanAndMarkNoteByIvkOnSolidityServlet), - // "/walletsolidity/scanandmarknotebyivk"); - // context.addServlet(new ServletHolder(scanNoteByIvkOnSolidityServlet), - // "/walletsolidity/scannotebyivk"); - // context.addServlet(new ServletHolder(scanNoteByOvkOnSolidityServlet), - // "/walletsolidity/scannotebyovk"); - // context.addServlet(new ServletHolder(isSpendOnSolidityServlet), - // "/walletsolidity/isspend"); + context.addServlet(new ServletHolder(getMerkleTreeVoucherInfoOnSolidityServlet), + "/walletsolidity/getmerkletreevoucherinfo"); + context.addServlet(new ServletHolder(scanAndMarkNoteByIvkOnSolidityServlet), + "/walletsolidity/scanandmarknotebyivk"); + context.addServlet(new ServletHolder(scanNoteByIvkOnSolidityServlet), + "/walletsolidity/scannotebyivk"); + context.addServlet(new ServletHolder(scanNoteByOvkOnSolidityServlet), + "/walletsolidity/scannotebyovk"); + context.addServlet(new ServletHolder(isSpendOnSolidityServlet), + "/walletsolidity/isspend"); context.addServlet(new ServletHolder(scanShieldedTRC20NotesbyIvkServlet), "/walletsolidity/scanshieldedtrc20notesbyivk"); context.addServlet(new ServletHolder(scanShieldedTRC20NotesbyOvkServlet), @@ -192,7 +192,6 @@ public void start() { context.addServlet(new ServletHolder(getTransactionInfoByBlockNumOnSolidityServlet), "/walletsolidity/gettransactioninfobyblocknum"); - // only for SolidityNode context.addServlet(new ServletHolder(getTransactionByIdOnSolidityServlet), "/walletsolidity/gettransactionbyid"); diff --git a/framework/src/main/resources/config-localtest.conf b/framework/src/main/resources/config-localtest.conf index c1575bc3961..ace6d28cc99 100644 --- a/framework/src/main/resources/config-localtest.conf +++ b/framework/src/main/resources/config-localtest.conf @@ -96,6 +96,10 @@ node { minParticipationRate = 0 + fullNodeAllowShieldedTransaction = true + + zenTokenId = 1000001 + # check the peer data transfer ,disconnect factor disconnectNumberFactor = 0.4 maxConnectNumberFactor = 0.8 @@ -272,6 +276,7 @@ vm = { committee = { allowCreationOfContracts = 1 //mainnet:0 (reset by committee),test:1 allowMultiSign = 1 //mainnet:0 (reset by committee),test:1 + allowShieldedTransaction = 1 //mainnet:0 (reset by committee),test:1 allowSameTokenName = 1 allowTvmTransferTrc10 = 1 allowTvmConstantinople = 1 From 2c11ca595cd6b7f36d7438eea1ef8490e86b752e Mon Sep 17 00:00:00 2001 From: Wenhua Zhang Date: Thu, 4 Jun 2020 23:23:22 +0800 Subject: [PATCH 02/60] feat: update shielded tx fee to be consistent with nile. TransactionFee: 10 trx CreateAccountFee: 10 trx --- .../main/java/org/tron/core/store/DynamicPropertiesStore.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java b/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java index 71ed26c7901..648a973c4b7 100644 --- a/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java +++ b/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java @@ -359,13 +359,13 @@ private DynamicPropertiesStore(@Value("properties") String dbName) { try { this.getShieldedTransactionFee(); } catch (IllegalArgumentException e) { - this.saveShieldedTransactionFee(100_000L); + this.saveShieldedTransactionFee(10_000_000L); // 10 } try { this.getShieldedTransactionCreateAccountFee(); } catch (IllegalArgumentException e) { - this.saveShieldedTransactionCreateAccountFee(1_000_000L); + this.saveShieldedTransactionCreateAccountFee(10_000_000L); // 10 } try { From 3e431cc09633deaa495b9bc5a9789187da1d03bb Mon Sep 17 00:00:00 2001 From: Matt Date: Mon, 6 Jul 2020 17:51:39 +0800 Subject: [PATCH 03/60] log vm shielded nile --- .../java/org/tron/core/db/KhaosDatabase.java | 109 +++++++++++++++++- 1 file changed, 107 insertions(+), 2 deletions(-) diff --git a/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java b/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java index 3a2b35be99a..8f8480440ad 100644 --- a/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java +++ b/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java @@ -13,6 +13,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import lombok.Getter; +import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -26,8 +27,87 @@ import org.tron.core.exception.UnLinkedBlockException; @Component +@Slf4j(topic = "DB") public class KhaosDatabase extends TronDatabase { + public static class Log { + Object blk_begin; + Object blk_prev; + Object head_begin; + Object head_prev; + Object mini_store_begin; + Object mini_store_prev; + Object maxCapcity_begin; + Object maxCapcity_prev; + Object numKblkMap_begin; + Object numKblkMap_prev; + Object hashKblkMap_begin; + Object hashKblkMap_prev; + Object head_num_begin; + Object head_num_prev; + + public void setBlk_begin(Object blk_begin) { + this.blk_prev = this.blk_begin; + this.blk_begin = blk_begin; + } + + public void setHead_begin(Object head_begin) { + this.head_prev = this.head_begin; + this.head_begin = head_begin; + } + + public void setMini_store_begin(Object mini_store_begin) { + this.mini_store_prev = this.mini_store_begin; + this.mini_store_begin = mini_store_begin; + } + + public void setMaxCapcity_begin(Object maxCapcity_begin) { + this.maxCapcity_prev = this.maxCapcity_begin; + this.maxCapcity_begin = maxCapcity_begin; + } + + public void setNumKblkMap_begin(Object numKblkMap_begin) { + this.numKblkMap_prev = this.numKblkMap_begin; + this.numKblkMap_begin = numKblkMap_begin; + } + + public void setHashKblkMap_begin(Object hashKblkMap_begin) { + this.hashKblkMap_prev = this.hashKblkMap_begin; + this.hashKblkMap_begin = hashKblkMap_begin; + } + + public void setHead_num_begin(Object head_num_begin) { + this.head_num_prev = this.head_num_begin; + this.head_num_begin = head_num_begin; + } + + public void print() { + logger.info("********************** " + this.toString()); + } + + @Override + public String toString() { + return "Log{" + + "blk_begin=" + blk_begin + + ", blk_prev=" + blk_prev + + ", head_begin=" + head_begin + + ", head_prev=" + head_prev + + ", mini_store_begin=" + mini_store_begin + + ", mini_store_prev=" + mini_store_prev + + ", maxCapcity_begin=" + maxCapcity_begin + + ", maxCapcity_prev=" + maxCapcity_prev + + ", numKblkMap_begin=" + numKblkMap_begin + + ", numKblkMap_prev=" + numKblkMap_prev + + ", hashKblkMap_begin=" + hashKblkMap_begin + + ", hashKblkMap_prev=" + hashKblkMap_prev + + ", head_num_begin=" + head_num_begin + + ", head_num_prev=" + head_num_prev + + '}'; + } + } + + public static Log log = new Log(); + private KhaosBlock head; @Getter private KhaosStore miniStore = new KhaosStore(); @@ -101,6 +181,9 @@ public BlockCapsule getBlock(Sha256Hash hash) { */ public BlockCapsule push(BlockCapsule blk) throws UnLinkedBlockException, BadNumberBlockException { + log.setBlk_begin(blk); + log.setHead_begin(blk); + log.setMini_store_begin(miniStore); KhaosBlock block = new KhaosBlock(blk); if (head != null && block.getParentHash() != Sha256Hash.ZERO_HASH) { KhaosBlock kblock = miniStore.getByHash(block.getParentHash()); @@ -111,6 +194,7 @@ public BlockCapsule push(BlockCapsule blk) } block.setParent(kblock); } else { + log.print(); miniUnlinkedStore.insert(block); throw new UnLinkedBlockException(); } @@ -153,7 +237,7 @@ public void setMaxSize(int maxSize) { * Find two block's most recent common parent block. */ public Pair, LinkedList> getBranch(Sha256Hash block1, - Sha256Hash block2) + Sha256Hash block2) throws NonCommonBlockException { LinkedList list1 = new LinkedList<>(); LinkedList list2 = new LinkedList<>(); @@ -287,6 +371,16 @@ public int hashCode() { return Objects.hash(id); } + + @Override + public String toString() { + return "KhaosBlock{" + + "blk=" + blk + + ", parent=" + parent.get() + + ", id=" + id + + ", num=" + num + + '}'; + } } public class KhaosStore { @@ -301,6 +395,10 @@ public class KhaosStore { @Override protected boolean removeEldestEntry(Map.Entry> entry) { + log.setHead_num_begin(head.num); + log.setMaxCapcity_begin(maxCapcity); + log.setNumKblkMap_begin(numKblkMap); + log.setHashKblkMap_begin(hashKblkMap); long minNum = Long.max(0L, head.num - maxCapcity); Map> minNumMap = numKblkMap.entrySet().stream() .filter(e -> e.getKey() < minNum) @@ -310,7 +408,6 @@ protected boolean removeEldestEntry(Map.Entry> entry numKblkMap.remove(k); v.forEach(b -> hashKblkMap.remove(b.id)); }); - return false; } }; @@ -357,5 +454,13 @@ public int size() { return hashKblkMap.size(); } + @Override + public String toString() { + return "KhaosStore{" + + "hashKblkMap=" + hashKblkMap + + ", maxCapcity=" + maxCapcity + + ", numKblkMap=" + numKblkMap + + '}'; + } } } From c024c88152cf1e63649087b9366fb3c4d8ed9588 Mon Sep 17 00:00:00 2001 From: pangpangfeng <7577288@qq.com> Date: Mon, 6 Jul 2020 19:27:20 +0800 Subject: [PATCH 04/60] No participation check --- .../src/main/java/org/tron/consensus/dpos/StateManager.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/consensus/src/main/java/org/tron/consensus/dpos/StateManager.java b/consensus/src/main/java/org/tron/consensus/dpos/StateManager.java index 12a04afcb28..560a3b27c42 100644 --- a/consensus/src/main/java/org/tron/consensus/dpos/StateManager.java +++ b/consensus/src/main/java/org/tron/consensus/dpos/StateManager.java @@ -51,13 +51,14 @@ public State getState() { return State.DUP_WITNESS; } - int participation = consensusDelegate.calculateFilledSlotsCount(); + /*int participation = consensusDelegate.calculateFilledSlotsCount(); int minParticipationRate = dposService.getMinParticipationRate(); if (participation < minParticipationRate) { logger .warn("Participation:{} < minParticipationRate:{}", participation, minParticipationRate); return State.LOW_PARTICIPATION; } + */ return State.OK; } From 26e0cffb55309a86d32e607f3d03106585355ee8 Mon Sep 17 00:00:00 2001 From: pangpangfeng <7577288@qq.com> Date: Thu, 30 Jul 2020 15:57:11 +0800 Subject: [PATCH 05/60] Add new hard fork to nile --- .../org/tron/core/utils/ProposalUtil.java | 2 +- .../java/org/tron/common/utils/ForkUtils.java | 34 +++++++++++++++++++ .../java/org/tron/core/config/Parameter.java | 2 +- .../org/tron/core/config/args/Parameter.java | 32 ++++++++++++----- .../core/store/DynamicPropertiesStore.java | 14 ++++---- .../java/org/tron/common/entity/NodeInfo.java | 7 ---- .../java/org/tron/core/config/args/Args.java | 1 - .../tron/core/services/NodeInfoService.java | 1 - 8 files changed, 68 insertions(+), 25 deletions(-) diff --git a/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java b/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java index c34293ddafe..e23c919c4d4 100644 --- a/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java +++ b/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java @@ -307,7 +307,7 @@ public static void validator(DynamicPropertiesStore dynamicPropertiesStore, Fork break; } case ALLOW_SHIELDED_TRC20_TRANSACTION: { - if (!forkUtils.pass(ForkBlockVersionEnum.VERSION_4_0)) { + if (!forkUtils.pass(ForkBlockVersionEnum.VERSION_4_0_1)) { throw new ContractValidateException( "Bad chain parameter id [ALLOW_SHIELDED_TRC20_TRANSACTION]"); } diff --git a/chainbase/src/main/java/org/tron/common/utils/ForkUtils.java b/chainbase/src/main/java/org/tron/common/utils/ForkUtils.java index 1a77e23b2fe..7e822dfdfc9 100644 --- a/chainbase/src/main/java/org/tron/common/utils/ForkUtils.java +++ b/chainbase/src/main/java/org/tron/common/utils/ForkUtils.java @@ -37,6 +37,14 @@ public boolean pass(ForkBlockVersionEnum forkBlockVersionEnum) { } public synchronized boolean pass(int version) { + if (version > ForkBlockVersionEnum.VERSION_4_0.getValue()) { + return passNew(version); + } else { + return passOld(version); + } + } + + private boolean passOld(int version) { if (version == ForkBlockVersionConsts.ENERGY_LIMIT) { return checkForEnergyLimit(); } @@ -45,6 +53,32 @@ public synchronized boolean pass(int version) { return check(stats); } + private boolean passNew(int version) { + ForkBlockVersionEnum versionEnum = ForkBlockVersionEnum.getForkBlockVersionEnum(version); + if (versionEnum == null) { + logger.error("not exist block version: {}", version); + return false; + } + long latestBlockTime = dynamicPropertiesStore.getLatestBlockHeaderTimestamp(); + long maintenanceTimeInterval = dynamicPropertiesStore.getMaintenanceTimeInterval(); + long hardForkTime = ((versionEnum.getHardForkTime() - 1) / maintenanceTimeInterval + 1) + * maintenanceTimeInterval; + if (latestBlockTime < hardForkTime) { + return false; + } + byte[] stats = dynamicPropertiesStore.statsByVersion(version); + if (stats == null || stats.length == 0) { + return false; + } + int count = 0; + for (int i = 0; i < stats.length; i++) { + if (check[i] == stats[i]) { + ++count; + } + } + return count >= versionEnum.getHardForkCount(); + } + // when block.version = 5, // it make block use new energy to handle transaction when block number >= 4727890L. // version !=5, skip this. diff --git a/chainbase/src/main/java/org/tron/core/config/Parameter.java b/chainbase/src/main/java/org/tron/core/config/Parameter.java index d3fbbefb75c..ac5f8f74354 100644 --- a/chainbase/src/main/java/org/tron/core/config/Parameter.java +++ b/chainbase/src/main/java/org/tron/core/config/Parameter.java @@ -18,7 +18,7 @@ public class ChainConstant { public static final int SINGLE_REPEAT = 1; public static final int BLOCK_FILLED_SLOTS_NUMBER = 128; public static final int MAX_FROZEN_NUMBER = 1; - public static final int BLOCK_VERSION = 16; + public static final int BLOCK_VERSION = 17; } public class NodeConstant { diff --git a/chainbase/src/main/java/org/tron/core/config/args/Parameter.java b/chainbase/src/main/java/org/tron/core/config/args/Parameter.java index c03568ebc42..216dbb785dd 100644 --- a/chainbase/src/main/java/org/tron/core/config/args/Parameter.java +++ b/chainbase/src/main/java/org/tron/core/config/args/Parameter.java @@ -5,19 +5,35 @@ public class Parameter { public enum ForkBlockVersionEnum { - ENERGY_LIMIT(5), - VERSION_3_2_2(6), - VERSION_3_5(7), - VERSION_3_6(8), - VERSION_3_6_5(9), - VERSION_3_6_6(10), - VERSION_4_0(16); + ENERGY_LIMIT(5, 0L, 0), + VERSION_3_2_2(6, 0L, 0), + VERSION_3_5(7, 0L, 0), + VERSION_3_6(8, 0L, 0), + VERSION_3_6_5(9, 0L, 0), + VERSION_3_6_6(10, 0L, 0), + VERSION_4_0(16, 0L, 0), + VERSION_4_0_1(17, 1596780000000L, 22);//GMT 2020-08-07 06:00:00 @Getter private int value; + @Getter + private long hardForkTime; + @Getter + private int hardForkCount; - ForkBlockVersionEnum(int value) { + ForkBlockVersionEnum(int value, long hardForkTime, int hardForkCount) { this.value = value; + this.hardForkTime = hardForkTime; + this.hardForkCount = hardForkCount; + } + + public static ForkBlockVersionEnum getForkBlockVersionEnum(int value) { + for (ForkBlockVersionEnum versionEnum : values()) { + if (versionEnum.getValue() == value) { + return versionEnum; + } + } + return null; } } diff --git a/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java b/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java index 648a973c4b7..8c941dec75b 100644 --- a/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java +++ b/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java @@ -91,7 +91,7 @@ public class DynamicPropertiesStore extends TronStoreWithRevoking private static final byte[] TOTAL_STORAGE_TAX = "TOTAL_STORAGE_TAX".getBytes(); private static final byte[] TOTAL_STORAGE_RESERVED = "TOTAL_STORAGE_RESERVED".getBytes(); private static final byte[] STORAGE_EXCHANGE_TAX_RATE = "STORAGE_EXCHANGE_TAX_RATE".getBytes(); - private static final byte[] FORK_CONTROLLER = "FORK_CONTROLLER".getBytes(); + private static final String FORK_CONTROLLER = "FORK_CONTROLLER"; private static final String FORK_PREFIX = "FORK_VERSION_"; //This value is only allowed to be 0, 1, -1 private static final byte[] REMOVE_THE_POWER_OF_THE_GR = "REMOVE_THE_POWER_OF_THE_GR".getBytes(); @@ -1766,8 +1766,9 @@ public void addTotalTransactionCost(long fee) { saveTotalTransactionCost(newValue); } - public void forked() { - put(FORK_CONTROLLER, new BytesCapsule(Boolean.toString(true).getBytes())); + public void forked(int version, boolean value) { + String forkKey = FORK_CONTROLLER + version; + put(forkKey.getBytes(), new BytesCapsule(Boolean.toString(value).getBytes())); } public void statsByVersion(int version, byte[] stats) { @@ -1780,9 +1781,10 @@ public byte[] statsByVersion(int version) { return revokingDB.getUnchecked(statsKey.getBytes()); } - public boolean getForked() { - byte[] value = revokingDB.getUnchecked(FORK_CONTROLLER); - return value == null ? Boolean.FALSE : Boolean.valueOf(new String(value)); + public Boolean getForked(int version) { + String forkKey = FORK_CONTROLLER + version; + byte[] value = revokingDB.getUnchecked(forkKey.getBytes()); + return value == null ? null : Boolean.valueOf(new String(value)); } /** diff --git a/framework/src/main/java/org/tron/common/entity/NodeInfo.java b/framework/src/main/java/org/tron/common/entity/NodeInfo.java index 9f3e1874c79..86d575539ea 100644 --- a/framework/src/main/java/org/tron/common/entity/NodeInfo.java +++ b/framework/src/main/java/org/tron/common/entity/NodeInfo.java @@ -505,7 +505,6 @@ public static class ConfigNodeInfo { /*node information*/ private String codeVersion; private String versionName; - private String versionNum; private String p2pVersion; private int listenPort; private boolean discoverEnable; @@ -542,13 +541,7 @@ public void setVersionName(String versionName) { this.versionName = versionName; } - public String getVersionNum() { - return versionNum; - } - public void setVersionNum(String versionNum) { - this.versionNum = versionNum; - } public String getP2pVersion() { return p2pVersion; diff --git a/framework/src/main/java/org/tron/core/config/args/Args.java b/framework/src/main/java/org/tron/core/config/args/Args.java index b8b3af41cae..c19740f6e1c 100644 --- a/framework/src/main/java/org/tron/core/config/args/Args.java +++ b/framework/src/main/java/org/tron/core/config/args/Args.java @@ -1456,7 +1456,6 @@ private static void logConfig() { logger.info("Backup priority: {}", args.getBackupPriority()); logger.info("************************ Code version *************************"); logger.info("Code version : {}", Version.getVersion()); - logger.info("Version name: {}", Version.versionName); logger.info("Version code: {}", Version.versionCode); logger.info("************************ DB config *************************"); logger.info("DB version : {}", args.getStorage().getDbVersion()); diff --git a/framework/src/main/java/org/tron/core/services/NodeInfoService.java b/framework/src/main/java/org/tron/core/services/NodeInfoService.java index 36103be5bec..517e8b8c369 100644 --- a/framework/src/main/java/org/tron/core/services/NodeInfoService.java +++ b/framework/src/main/java/org/tron/core/services/NodeInfoService.java @@ -166,7 +166,6 @@ private void setConfigNodeInfo(NodeInfo nodeInfo) { ConfigNodeInfo configNodeInfo = new ConfigNodeInfo(); configNodeInfo.setCodeVersion(Version.getVersion()); configNodeInfo.setVersionName(Version.versionName); - configNodeInfo.setVersionNum(Version.versionCode); configNodeInfo.setP2pVersion(String.valueOf(args.getNodeP2pVersion())); configNodeInfo.setListenPort(args.getNodeListenPort()); configNodeInfo.setDiscoverEnable(args.isNodeDiscoveryEnable()); From 0fd3ba37fac5ddce62345f0f0b85b68556d4913f Mon Sep 17 00:00:00 2001 From: Wenhua Zhang Date: Mon, 24 Aug 2020 02:53:41 +0800 Subject: [PATCH 06/60] feat: add some debug log --- .../tron/core/actuator/MarketSellAssetActuator.java | 6 ++++++ .../main/java/org/tron/core/db2/core/Chainbase.java | 10 ++++++++++ .../tron/core/store/MarketPairPriceToOrderStore.java | 12 +++++++++++- 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java b/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java index 1dfd15fcca5..e800fbe0243 100644 --- a/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java @@ -304,12 +304,18 @@ private void matchOrder(MarketOrderCapsule takerCapsule, MarketPrice takerPrice, TransactionResultCapsule ret, AccountCapsule takerAccountCapsule) throws ItemNotFoundException, ContractValidateException { + String functionName = "matchOrder"; + logger.info(String.format("[%s] takerCapsule is sell_id: %s, buy_id: %s", + functionName, new String(sellTokenID), new String(buyTokenID))); + byte[] makerSellTokenID = buyTokenID; byte[] makerBuyTokenID = sellTokenID; byte[] makerPair = MarketUtils.createPairKey(makerSellTokenID, makerBuyTokenID); // makerPair not exists long makerPriceNumber = pairToPriceStore.getPriceNum(makerPair); + logger.info(String.format("[%s] makerPriceNumber is %d", functionName, makerPriceNumber)); + if (makerPriceNumber == 0) { return; } diff --git a/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java b/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java index a2896c87dce..10531cff90b 100644 --- a/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java +++ b/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java @@ -2,7 +2,9 @@ import com.google.common.collect.Maps; import com.google.common.collect.Streams; +import java.lang.reflect.Array; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; @@ -11,6 +13,7 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; +import lombok.extern.slf4j.Slf4j; import org.tron.common.utils.ByteUtil; import org.tron.core.capsule.utils.MarketUtils; import org.tron.core.db2.common.IRevokingDB; @@ -21,6 +24,7 @@ import org.tron.core.db2.common.WrappedByteArray; import org.tron.core.exception.ItemNotFoundException; +@Slf4j(topic = "DB") public class Chainbase implements IRevokingDB { // public static Map assetsAddress = new HashMap<>(); // key = name , value = address @@ -231,10 +235,16 @@ private List getKeysNext(Snapshot head, byte[] key, long limit) { // snapshot and levelDB will have duplicated key, so need to check it before, // and remove the key which has been deleted snapshotList.forEach(ssKey -> { + logger.info(String.format("[Chainbase.getKeysNext] key is %s, op is %s", + Arrays.toString(ssKey.getBytes()), collectionList.get(ssKey).toString())); + if (!keyList.contains(ssKey)) { + logger.info(String.format("[Chainbase.getKeysNext] add key: %s", Arrays.toString(ssKey.getBytes()))); keyList.add(ssKey); } + // TODO: 会不会多删除了数据? if (collectionList.get(ssKey) == Operator.DELETE) { + logger.info(String.format("[Chainbase.getKeysNext] delete key: %s", Arrays.toString(ssKey.getBytes()))); keyList.remove(ssKey); } }); diff --git a/chainbase/src/main/java/org/tron/core/store/MarketPairPriceToOrderStore.java b/chainbase/src/main/java/org/tron/core/store/MarketPairPriceToOrderStore.java index 605952328ed..6601bef4a3c 100644 --- a/chainbase/src/main/java/org/tron/core/store/MarketPairPriceToOrderStore.java +++ b/chainbase/src/main/java/org/tron/core/store/MarketPairPriceToOrderStore.java @@ -1,8 +1,10 @@ package org.tron.core.store; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.List; +import lombok.extern.slf4j.Slf4j; import org.iq80.leveldb.Options; import org.rocksdb.ComparatorOptions; import org.rocksdb.DirectComparator; @@ -18,6 +20,7 @@ import org.tron.core.db.TronStoreWithRevoking; import org.tron.core.exception.ItemNotFoundException; +@Slf4j(topic = "DB") @Component public class MarketPairPriceToOrderStore extends TronStoreWithRevoking { @@ -69,11 +72,18 @@ public List getPriceKeysList(byte[] sellTokenId, byte[] buyTokenId, long public List getPriceKeysList(byte[] headKey, long count, long totalCount, boolean skip) { List result = new ArrayList<>(); + logger.info(String.format("[getPriceKeysList] headKey is %s, count: %d, totalCount: %d", + new String(headKey), count, totalCount)); + if (has(headKey)) { long limit = count > totalCount ? totalCount : count; + logger.info(String.format("[getPriceKeysList] limit: %d", limit)); if (skip) { // need to get one more - result = getKeysNext(headKey, limit + 1).subList(1, (int)(limit + 1)); + result = getKeysNext(headKey, limit + 1); + logger.info(String.format("[getPriceKeysList] allResult num is %d, is %s,", + result.size(), Arrays.toString(result.toArray()))); + result = result.subList(1, (int)(limit + 1)); } else { result = getKeysNext(headKey, limit); } From a086201db992c8df6aaac8383117b3bca9e0c3f7 Mon Sep 17 00:00:00 2001 From: sean-liu55 Date: Mon, 24 Aug 2020 13:33:25 +0800 Subject: [PATCH 07/60] add filter --- .../src/main/java/org/tron/core/db2/core/Chainbase.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java b/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java index 10531cff90b..6b14a2d5e7d 100644 --- a/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java +++ b/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java @@ -229,8 +229,14 @@ private List getKeysNext(Snapshot head, byte[] key, long limit) { .forEach(e -> levelDBList.add(WrappedByteArray.of(e))); } + // just get the same token pair + List levelDBListFiltered = new ArrayList<>(); + levelDBListFiltered = levelDBList.stream() + .filter(e -> MarketUtils.pairKeyIsEqual(e.getBytes(), key)) + .collect(Collectors.toList()); + List keyList = new ArrayList<>(); - keyList.addAll(levelDBList); + keyList.addAll(levelDBListFiltered); // snapshot and levelDB will have duplicated key, so need to check it before, // and remove the key which has been deleted From b7e60fde4250d8faf5ebce2a0f441340ad3f8eeb Mon Sep 17 00:00:00 2001 From: sean-liu55 Date: Mon, 24 Aug 2020 14:09:05 +0800 Subject: [PATCH 08/60] add log --- .../java/org/tron/core/db2/core/Chainbase.java | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java b/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java index 6b14a2d5e7d..2b1f54adc1b 100644 --- a/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java +++ b/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java @@ -232,8 +232,13 @@ private List getKeysNext(Snapshot head, byte[] key, long limit) { // just get the same token pair List levelDBListFiltered = new ArrayList<>(); levelDBListFiltered = levelDBList.stream() - .filter(e -> MarketUtils.pairKeyIsEqual(e.getBytes(), key)) - .collect(Collectors.toList()); + .filter(e -> MarketUtils.pairKeyIsEqual(e.getBytes(), key)) + .collect(Collectors.toList()); + if (levelDBListFiltered.size() != levelDBListFiltered.size()) { + logger.warn( + "levelDBListFiltered.size():" + levelDBListFiltered.size() + + ",levelDBListFiltered.size():" + levelDBListFiltered.size()); + } List keyList = new ArrayList<>(); keyList.addAll(levelDBListFiltered); @@ -245,12 +250,14 @@ private List getKeysNext(Snapshot head, byte[] key, long limit) { Arrays.toString(ssKey.getBytes()), collectionList.get(ssKey).toString())); if (!keyList.contains(ssKey)) { - logger.info(String.format("[Chainbase.getKeysNext] add key: %s", Arrays.toString(ssKey.getBytes()))); + logger.info(String + .format("[Chainbase.getKeysNext] add key: %s", Arrays.toString(ssKey.getBytes()))); keyList.add(ssKey); } // TODO: 会不会多删除了数据? if (collectionList.get(ssKey) == Operator.DELETE) { - logger.info(String.format("[Chainbase.getKeysNext] delete key: %s", Arrays.toString(ssKey.getBytes()))); + logger.info(String + .format("[Chainbase.getKeysNext] delete key: %s", Arrays.toString(ssKey.getBytes()))); keyList.remove(ssKey); } }); From ec5050be665b7e48f541673224ca48a2833aede4 Mon Sep 17 00:00:00 2001 From: Wenhua Zhang Date: Mon, 24 Aug 2020 15:24:15 +0800 Subject: [PATCH 09/60] fix: data from snapshot is old_time first --- .../main/java/org/tron/core/db2/core/Chainbase.java | 1 - .../java/org/tron/core/db2/core/SnapshotImpl.java | 11 +++-------- 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java b/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java index 6b14a2d5e7d..4f33f4b2d0a 100644 --- a/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java +++ b/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java @@ -248,7 +248,6 @@ private List getKeysNext(Snapshot head, byte[] key, long limit) { logger.info(String.format("[Chainbase.getKeysNext] add key: %s", Arrays.toString(ssKey.getBytes()))); keyList.add(ssKey); } - // TODO: 会不会多删除了数据? if (collectionList.get(ssKey) == Operator.DELETE) { logger.info(String.format("[Chainbase.getKeysNext] delete key: %s", Arrays.toString(ssKey.getBytes()))); keyList.remove(ssKey); diff --git a/chainbase/src/main/java/org/tron/core/db2/core/SnapshotImpl.java b/chainbase/src/main/java/org/tron/core/db2/core/SnapshotImpl.java index a8a900e51a8..403a0ad988d 100644 --- a/chainbase/src/main/java/org/tron/core/db2/core/SnapshotImpl.java +++ b/chainbase/src/main/java/org/tron/core/db2/core/SnapshotImpl.java @@ -117,6 +117,7 @@ synchronized void collect(Map all) { } /** + * Note: old --> new * In the snapshot, there may be same keys. * If we use Map to get all the data, the later will overwrite the previous value. * So, if we use list, we need to exclude duplicate keys. @@ -127,14 +128,8 @@ synchronized void collectUnique(Map all) { Snapshot next = getRoot().getNext(); while (next != null) { Streams.stream(((SnapshotImpl) next).db) - .forEach(e -> { - WrappedByteArray key = WrappedByteArray.of(e.getKey().getBytes()); - if (!all.containsKey(key)) { - all.put(WrappedByteArray.of(e.getKey().getBytes()), - e.getValue().getOperator()); - } - - }); + .forEach(e -> all.put(WrappedByteArray.of(e.getKey().getBytes()), + e.getValue().getOperator())); next = next.getNext(); } } From a91c053d091988550d1575479784abf26cacd9bd Mon Sep 17 00:00:00 2001 From: Wenhua Zhang Date: Mon, 24 Aug 2020 18:07:26 +0800 Subject: [PATCH 10/60] typo: remove log --- .../core/actuator/MarketSellAssetActuator.java | 5 ----- .../java/org/tron/core/db2/core/Chainbase.java | 16 ---------------- .../core/store/MarketPairPriceToOrderStore.java | 12 +----------- 3 files changed, 1 insertion(+), 32 deletions(-) diff --git a/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java b/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java index e800fbe0243..01d8ec40330 100644 --- a/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java @@ -304,17 +304,12 @@ private void matchOrder(MarketOrderCapsule takerCapsule, MarketPrice takerPrice, TransactionResultCapsule ret, AccountCapsule takerAccountCapsule) throws ItemNotFoundException, ContractValidateException { - String functionName = "matchOrder"; - logger.info(String.format("[%s] takerCapsule is sell_id: %s, buy_id: %s", - functionName, new String(sellTokenID), new String(buyTokenID))); - byte[] makerSellTokenID = buyTokenID; byte[] makerBuyTokenID = sellTokenID; byte[] makerPair = MarketUtils.createPairKey(makerSellTokenID, makerBuyTokenID); // makerPair not exists long makerPriceNumber = pairToPriceStore.getPriceNum(makerPair); - logger.info(String.format("[%s] makerPriceNumber is %d", functionName, makerPriceNumber)); if (makerPriceNumber == 0) { return; diff --git a/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java b/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java index 8e38a77838e..ca1f51cc7a5 100644 --- a/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java +++ b/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java @@ -2,9 +2,7 @@ import com.google.common.collect.Maps; import com.google.common.collect.Streams; -import java.lang.reflect.Array; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; @@ -13,7 +11,6 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; -import lombok.extern.slf4j.Slf4j; import org.tron.common.utils.ByteUtil; import org.tron.core.capsule.utils.MarketUtils; import org.tron.core.db2.common.IRevokingDB; @@ -24,7 +21,6 @@ import org.tron.core.db2.common.WrappedByteArray; import org.tron.core.exception.ItemNotFoundException; -@Slf4j(topic = "DB") public class Chainbase implements IRevokingDB { // public static Map assetsAddress = new HashMap<>(); // key = name , value = address @@ -234,11 +230,6 @@ private List getKeysNext(Snapshot head, byte[] key, long limit) { levelDBListFiltered = levelDBList.stream() .filter(e -> MarketUtils.pairKeyIsEqual(e.getBytes(), key)) .collect(Collectors.toList()); - if (levelDBListFiltered.size() != levelDBListFiltered.size()) { - logger.warn( - "levelDBListFiltered.size():" + levelDBListFiltered.size() + - ",levelDBListFiltered.size():" + levelDBListFiltered.size()); - } List keyList = new ArrayList<>(); keyList.addAll(levelDBListFiltered); @@ -246,17 +237,10 @@ private List getKeysNext(Snapshot head, byte[] key, long limit) { // snapshot and levelDB will have duplicated key, so need to check it before, // and remove the key which has been deleted snapshotList.forEach(ssKey -> { - logger.info(String.format("[Chainbase.getKeysNext] key is %s, op is %s", - Arrays.toString(ssKey.getBytes()), collectionList.get(ssKey).toString())); - if (!keyList.contains(ssKey)) { - logger.info(String - .format("[Chainbase.getKeysNext] add key: %s", Arrays.toString(ssKey.getBytes()))); keyList.add(ssKey); } if (collectionList.get(ssKey) == Operator.DELETE) { - logger.info(String - .format("[Chainbase.getKeysNext] delete key: %s", Arrays.toString(ssKey.getBytes()))); keyList.remove(ssKey); } }); diff --git a/chainbase/src/main/java/org/tron/core/store/MarketPairPriceToOrderStore.java b/chainbase/src/main/java/org/tron/core/store/MarketPairPriceToOrderStore.java index 6601bef4a3c..605952328ed 100644 --- a/chainbase/src/main/java/org/tron/core/store/MarketPairPriceToOrderStore.java +++ b/chainbase/src/main/java/org/tron/core/store/MarketPairPriceToOrderStore.java @@ -1,10 +1,8 @@ package org.tron.core.store; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; -import lombok.extern.slf4j.Slf4j; import org.iq80.leveldb.Options; import org.rocksdb.ComparatorOptions; import org.rocksdb.DirectComparator; @@ -20,7 +18,6 @@ import org.tron.core.db.TronStoreWithRevoking; import org.tron.core.exception.ItemNotFoundException; -@Slf4j(topic = "DB") @Component public class MarketPairPriceToOrderStore extends TronStoreWithRevoking { @@ -72,18 +69,11 @@ public List getPriceKeysList(byte[] sellTokenId, byte[] buyTokenId, long public List getPriceKeysList(byte[] headKey, long count, long totalCount, boolean skip) { List result = new ArrayList<>(); - logger.info(String.format("[getPriceKeysList] headKey is %s, count: %d, totalCount: %d", - new String(headKey), count, totalCount)); - if (has(headKey)) { long limit = count > totalCount ? totalCount : count; - logger.info(String.format("[getPriceKeysList] limit: %d", limit)); if (skip) { // need to get one more - result = getKeysNext(headKey, limit + 1); - logger.info(String.format("[getPriceKeysList] allResult num is %d, is %s,", - result.size(), Arrays.toString(result.toArray()))); - result = result.subList(1, (int)(limit + 1)); + result = getKeysNext(headKey, limit + 1).subList(1, (int)(limit + 1)); } else { result = getKeysNext(headKey, limit); } From 44467552d8405bc6ff74d5366e86d4d73bcdcb9d Mon Sep 17 00:00:00 2001 From: Wenhua Zhang Date: Mon, 24 Aug 2020 23:39:06 +0800 Subject: [PATCH 11/60] fix: fix test --- .../org/tron/core/db/MarketPairPriceToOrderStoreTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java b/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java index c14281c68d6..8eb795fef39 100755 --- a/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java @@ -768,6 +768,7 @@ private boolean randomOp() { /** * From this test we know that, if we use getKeysNext to get the priceKey list of one token pair, * we should know the count of priceKey previously. + * Update: getKeysNext will just return (sellToken, buyToken)'s price, so the result will be 0 now. * */ @Test public void testGetKeysNextNotExitsWithRandom() { @@ -779,6 +780,7 @@ public void testGetKeysNextNotExitsWithRandom() { int sellToken = randomInt(100, 9999); int buyToken = randomInt(10000, 9999999); + // randomSellToken != sellToken, randomBuyToken != buyToken for (int i = 0; i < 1000; i++) { int randomSellToken = randomOp() ? sellToken + randomInt(1, maxInt) : sellToken - randomInt(1, sellToken - 1); @@ -802,7 +804,7 @@ public void testGetKeysNextNotExitsWithRandom() { byte[] headKey = MarketUtils.getPairPriceHeadKey(sellTokenId, buyTokenId); List list = marketPairPriceToOrderStore.getKeysNext(headKey, 100); - Assert.assertNotEquals(0, list.size()); + Assert.assertEquals(0, list.size()); } @Test From 931bfeb504a1b6537ba66352c5acabf0d257cddc Mon Sep 17 00:00:00 2001 From: sean-liu55 Date: Tue, 25 Aug 2020 09:26:55 +0800 Subject: [PATCH 12/60] fix checkstyle --- .../java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java b/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java index c14281c68d6..b96f3dae937 100755 --- a/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java @@ -768,7 +768,7 @@ private boolean randomOp() { /** * From this test we know that, if we use getKeysNext to get the priceKey list of one token pair, * we should know the count of priceKey previously. - * */ + */ @Test public void testGetKeysNextNotExitsWithRandom() { int maxInt = 99999999; From bf2e61ad7939468acdfebd67aa18343519ec6397 Mon Sep 17 00:00:00 2001 From: sean-liu55 Date: Tue, 25 Aug 2020 09:30:33 +0800 Subject: [PATCH 13/60] fix checkstyle --- .../org/tron/core/db/MarketPairPriceToOrderStoreTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java b/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java index 8eb795fef39..a264b33ee98 100755 --- a/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java @@ -767,9 +767,9 @@ private boolean randomOp() { /** * From this test we know that, if we use getKeysNext to get the priceKey list of one token pair, - * we should know the count of priceKey previously. - * Update: getKeysNext will just return (sellToken, buyToken)'s price, so the result will be 0 now. - * */ + * we should know the count of priceKey previously. Update: getKeysNext will just return + * (sellToken, buyToken)'s price, so the result will be 0 now. + */ @Test public void testGetKeysNextNotExitsWithRandom() { int maxInt = 99999999; From 21683a6ec2501fe995dec2d1ec2b91de73120b5e Mon Sep 17 00:00:00 2001 From: Wenhua Zhang Date: Tue, 25 Aug 2020 18:22:49 +0800 Subject: [PATCH 14/60] feat: add dex pbft api --- .../org/tron/core/services/RpcApiService.java | 2 +- .../interfaceOnPBFT/RpcApiServiceOnPBFT.java | 49 +++++++++++++++++++ .../GetMarketOrderByAccountOnPBFTServlet.java | 26 ++++++++++ .../http/GetMarketOrderByIdOnPBFTServlet.java | 26 ++++++++++ ...GetMarketOrderListByPairOnPBFTServlet.java | 26 ++++++++++ .../http/GetMarketPairListOnPBFTServlet.java | 26 ++++++++++ .../GetMarketPriceByPairOnPBFTServlet.java | 26 ++++++++++ .../http/PBFT/HttpApiOnPBFTService.java | 28 +++++++++++ 8 files changed, 208 insertions(+), 1 deletion(-) create mode 100644 framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetMarketOrderByAccountOnPBFTServlet.java create mode 100644 framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetMarketOrderByIdOnPBFTServlet.java create mode 100644 framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetMarketOrderListByPairOnPBFTServlet.java create mode 100644 framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetMarketPairListOnPBFTServlet.java create mode 100644 framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetMarketPriceByPairOnPBFTServlet.java diff --git a/framework/src/main/java/org/tron/core/services/RpcApiService.java b/framework/src/main/java/org/tron/core/services/RpcApiService.java index 5a6987d4bcc..92e3c448719 100755 --- a/framework/src/main/java/org/tron/core/services/RpcApiService.java +++ b/framework/src/main/java/org/tron/core/services/RpcApiService.java @@ -887,7 +887,7 @@ public void getMarketPriceByPair(MarketOrderPair request, } @Override - public void getMarketOrderListByPair(org.tron.protos.Protocol.MarketOrderPair request, + public void getMarketOrderListByPair(MarketOrderPair request, StreamObserver responseObserver) { try { MarketOrderList orderPairList = wallet diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/RpcApiServiceOnPBFT.java b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/RpcApiServiceOnPBFT.java index 712366f4a2e..85a0d3bbbfa 100755 --- a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/RpcApiServiceOnPBFT.java +++ b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/RpcApiServiceOnPBFT.java @@ -40,6 +40,11 @@ import org.tron.protos.Protocol.Block; import org.tron.protos.Protocol.DynamicProperties; import org.tron.protos.Protocol.Exchange; +import org.tron.protos.Protocol.MarketOrder; +import org.tron.protos.Protocol.MarketOrderList; +import org.tron.protos.Protocol.MarketOrderPair; +import org.tron.protos.Protocol.MarketOrderPairList; +import org.tron.protos.Protocol.MarketPriceList; import org.tron.protos.Protocol.Transaction; import org.tron.protos.Protocol.TransactionInfo; import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; @@ -407,5 +412,49 @@ public void isSpend(NoteParameters request, StreamObserver response ); } + @Override + public void getMarketOrderByAccount(BytesMessage request, + StreamObserver responseObserver) { + walletOnPBFT.futureGet( + () -> rpcApiService.getWalletSolidityApi() + .getMarketOrderByAccount(request, responseObserver) + ); + } + + @Override + public void getMarketOrderById(BytesMessage request, + StreamObserver responseObserver) { + walletOnPBFT.futureGet( + () -> rpcApiService.getWalletSolidityApi() + .getMarketOrderById(request, responseObserver) + ); + } + + @Override + public void getMarketPriceByPair(MarketOrderPair request, + StreamObserver responseObserver) { + walletOnPBFT.futureGet( + () -> rpcApiService.getWalletSolidityApi() + .getMarketPriceByPair(request, responseObserver) + ); + } + + @Override + public void getMarketOrderListByPair(MarketOrderPair request, + StreamObserver responseObserver) { + walletOnPBFT.futureGet( + () -> rpcApiService.getWalletSolidityApi() + .getMarketOrderListByPair(request, responseObserver) + ); + } + + @Override + public void getMarketPairList(EmptyMessage request, + StreamObserver responseObserver) { + walletOnPBFT.futureGet( + () -> rpcApiService.getWalletSolidityApi() + .getMarketPairList(request, responseObserver) + ); + } } } diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetMarketOrderByAccountOnPBFTServlet.java b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetMarketOrderByAccountOnPBFTServlet.java new file mode 100644 index 00000000000..7fa308c3abc --- /dev/null +++ b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetMarketOrderByAccountOnPBFTServlet.java @@ -0,0 +1,26 @@ +package org.tron.core.services.interfaceOnPBFT.http; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.tron.core.services.http.GetMarketOrderByAccountServlet; +import org.tron.core.services.interfaceOnPBFT.WalletOnPBFT; + + +@Component +@Slf4j(topic = "API") +public class GetMarketOrderByAccountOnPBFTServlet extends GetMarketOrderByAccountServlet { + + @Autowired + private WalletOnPBFT walletOnPBFT; + + protected void doGet(HttpServletRequest request, HttpServletResponse response) { + walletOnPBFT.futureGet(() -> super.doGet(request, response)); + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) { + walletOnPBFT.futureGet(() -> super.doPost(request, response)); + } +} diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetMarketOrderByIdOnPBFTServlet.java b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetMarketOrderByIdOnPBFTServlet.java new file mode 100644 index 00000000000..63809fd032c --- /dev/null +++ b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetMarketOrderByIdOnPBFTServlet.java @@ -0,0 +1,26 @@ +package org.tron.core.services.interfaceOnPBFT.http; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.tron.core.services.http.GetMarketOrderByIdServlet; +import org.tron.core.services.interfaceOnPBFT.WalletOnPBFT; + + +@Component +@Slf4j(topic = "API") +public class GetMarketOrderByIdOnPBFTServlet extends GetMarketOrderByIdServlet { + + @Autowired + private WalletOnPBFT walletOnPBFT; + + protected void doGet(HttpServletRequest request, HttpServletResponse response) { + walletOnPBFT.futureGet(() -> super.doGet(request, response)); + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) { + walletOnPBFT.futureGet(() -> super.doPost(request, response)); + } +} diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetMarketOrderListByPairOnPBFTServlet.java b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetMarketOrderListByPairOnPBFTServlet.java new file mode 100644 index 00000000000..b18dde73651 --- /dev/null +++ b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetMarketOrderListByPairOnPBFTServlet.java @@ -0,0 +1,26 @@ +package org.tron.core.services.interfaceOnPBFT.http; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.tron.core.services.http.GetMarketOrderListByPairServlet; +import org.tron.core.services.interfaceOnPBFT.WalletOnPBFT; + + +@Component +@Slf4j(topic = "API") +public class GetMarketOrderListByPairOnPBFTServlet extends GetMarketOrderListByPairServlet { + + @Autowired + private WalletOnPBFT walletOnPBFT; + + protected void doGet(HttpServletRequest request, HttpServletResponse response) { + walletOnPBFT.futureGet(() -> super.doGet(request, response)); + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) { + walletOnPBFT.futureGet(() -> super.doPost(request, response)); + } +} diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetMarketPairListOnPBFTServlet.java b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetMarketPairListOnPBFTServlet.java new file mode 100644 index 00000000000..4d3f69c9132 --- /dev/null +++ b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetMarketPairListOnPBFTServlet.java @@ -0,0 +1,26 @@ +package org.tron.core.services.interfaceOnPBFT.http; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.tron.core.services.http.GetMarketPairListServlet; +import org.tron.core.services.interfaceOnPBFT.WalletOnPBFT; + + +@Component +@Slf4j(topic = "API") +public class GetMarketPairListOnPBFTServlet extends GetMarketPairListServlet { + + @Autowired + private WalletOnPBFT walletOnPBFT; + + protected void doGet(HttpServletRequest request, HttpServletResponse response) { + walletOnPBFT.futureGet(() -> super.doGet(request, response)); + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) { + walletOnPBFT.futureGet(() -> super.doPost(request, response)); + } +} diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetMarketPriceByPairOnPBFTServlet.java b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetMarketPriceByPairOnPBFTServlet.java new file mode 100644 index 00000000000..330cf2c2552 --- /dev/null +++ b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/GetMarketPriceByPairOnPBFTServlet.java @@ -0,0 +1,26 @@ +package org.tron.core.services.interfaceOnPBFT.http; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.tron.core.services.http.GetMarketPriceByPairServlet; +import org.tron.core.services.interfaceOnPBFT.WalletOnPBFT; + + +@Component +@Slf4j(topic = "API") +public class GetMarketPriceByPairOnPBFTServlet extends GetMarketPriceByPairServlet { + + @Autowired + private WalletOnPBFT walletOnPBFT; + + protected void doGet(HttpServletRequest request, HttpServletResponse response) { + walletOnPBFT.futureGet(() -> super.doGet(request, response)); + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) { + walletOnPBFT.futureGet(() -> super.doPost(request, response)); + } +} diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/PBFT/HttpApiOnPBFTService.java b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/PBFT/HttpApiOnPBFTService.java index fed3082efe4..f463d6a06d4 100644 --- a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/PBFT/HttpApiOnPBFTService.java +++ b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/PBFT/HttpApiOnPBFTService.java @@ -27,6 +27,11 @@ import org.tron.core.services.interfaceOnPBFT.http.GetDelegatedResourceAccountIndexOnPBFTServlet; import org.tron.core.services.interfaceOnPBFT.http.GetDelegatedResourceOnPBFTServlet; import org.tron.core.services.interfaceOnPBFT.http.GetExchangeByIdOnPBFTServlet; +import org.tron.core.services.interfaceOnPBFT.http.GetMarketOrderByAccountOnPBFTServlet; +import org.tron.core.services.interfaceOnPBFT.http.GetMarketOrderByIdOnPBFTServlet; +import org.tron.core.services.interfaceOnPBFT.http.GetMarketOrderListByPairOnPBFTServlet; +import org.tron.core.services.interfaceOnPBFT.http.GetMarketPairListOnPBFTServlet; +import org.tron.core.services.interfaceOnPBFT.http.GetMarketPriceByPairOnPBFTServlet; import org.tron.core.services.interfaceOnPBFT.http.GetMerkleTreeVoucherInfoOnPBFTServlet; import org.tron.core.services.interfaceOnPBFT.http.GetNodeInfoOnPBFTServlet; import org.tron.core.services.interfaceOnPBFT.http.GetNowBlockOnPBFTServlet; @@ -115,6 +120,17 @@ public class HttpApiOnPBFTService implements Service { @Autowired private LiteFnQueryHttpFilter liteFnQueryHttpFilter; + @Autowired + private GetMarketOrderByAccountOnPBFTServlet getMarketOrderByAccountOnPBFTServlet; + @Autowired + private GetMarketOrderByIdOnPBFTServlet getMarketOrderByIdOnPBFTServlet; + @Autowired + private GetMarketPriceByPairOnPBFTServlet getMarketPriceByPairOnPBFTServlet; + @Autowired + private GetMarketOrderListByPairOnPBFTServlet getMarketOrderListByPairOnPBFTServlet; + @Autowired + private GetMarketPairListOnPBFTServlet getMarketPairListOnPBFTServlet; + @Override public void init() { @@ -179,6 +195,18 @@ public void start() { context.addServlet(new ServletHolder(getNodeInfoOnPBFTServlet), "/getnodeinfo"); context.addServlet(new ServletHolder(getBrokerageServlet), "/getBrokerage"); context.addServlet(new ServletHolder(getRewardServlet), "/getReward"); + + context.addServlet(new ServletHolder(getMarketOrderByAccountOnPBFTServlet), + "/getmarketorderbyaccount"); + context.addServlet(new ServletHolder(getMarketOrderByIdOnPBFTServlet), + "/getmarketorderbyid"); + context.addServlet(new ServletHolder(getMarketPriceByPairOnPBFTServlet), + "/getmarketpricebypair"); + context.addServlet(new ServletHolder(getMarketOrderListByPairOnPBFTServlet), + "/getmarketorderlistbypair"); + context.addServlet(new ServletHolder(getMarketPairListOnPBFTServlet), + "/getmarketpairlist"); + int maxHttpConnectNumber = Args.getInstance().getMaxHttpConnectNumber(); if (maxHttpConnectNumber > 0) { server.addBean(new ConnectionLimit(maxHttpConnectNumber, server)); From 60e6f1b0f6e662b65ea886d502e9df5dc0b815c9 Mon Sep 17 00:00:00 2001 From: "federico.zhen" Date: Wed, 26 Aug 2020 12:25:31 +0800 Subject: [PATCH 15/60] feat: add the shielded trc20 contract api --- .../interfaceOnPBFT/RpcApiServiceOnPBFT.java | 33 +++++++++++++++++++ ...edTRC20ContractNoteSpentOnPBFTServlet.java | 26 +++++++++++++++ .../http/PBFT/HttpApiOnPBFTService.java | 18 ++++++++++ ...nShieldedTRC20NotesByIvkOnPBFTServlet.java | 25 ++++++++++++++ ...nShieldedTRC20NotesByOvkOnPBFTServlet.java | 24 ++++++++++++++ 5 files changed, 126 insertions(+) create mode 100644 framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/IsShieldedTRC20ContractNoteSpentOnPBFTServlet.java create mode 100644 framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/ScanShieldedTRC20NotesByIvkOnPBFTServlet.java create mode 100644 framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/ScanShieldedTRC20NotesByOvkOnPBFTServlet.java diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/RpcApiServiceOnPBFT.java b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/RpcApiServiceOnPBFT.java index 85a0d3bbbfa..2547d801197 100755 --- a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/RpcApiServiceOnPBFT.java +++ b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/RpcApiServiceOnPBFT.java @@ -16,12 +16,17 @@ import org.tron.api.GrpcAPI.BlockExtention; import org.tron.api.GrpcAPI.BlockReference; import org.tron.api.GrpcAPI.BytesMessage; +import org.tron.api.GrpcAPI.DecryptNotesTRC20; import org.tron.api.GrpcAPI.DelegatedResourceList; import org.tron.api.GrpcAPI.DelegatedResourceMessage; import org.tron.api.GrpcAPI.EmptyMessage; import org.tron.api.GrpcAPI.ExchangeList; +import org.tron.api.GrpcAPI.IvkDecryptTRC20Parameters; +import org.tron.api.GrpcAPI.NfTRC20Parameters; import org.tron.api.GrpcAPI.NoteParameters; +import org.tron.api.GrpcAPI.NullifierResult; import org.tron.api.GrpcAPI.NumberMessage; +import org.tron.api.GrpcAPI.OvkDecryptTRC20Parameters; import org.tron.api.GrpcAPI.PaginatedMessage; import org.tron.api.GrpcAPI.SpendResult; import org.tron.api.GrpcAPI.TransactionExtention; @@ -456,5 +461,33 @@ public void getMarketPairList(EmptyMessage request, .getMarketPairList(request, responseObserver) ); } + + @Override + public void scanShieldedTRC20NotesByIvk(IvkDecryptTRC20Parameters request, + StreamObserver responseObserver) { + walletOnPBFT.futureGet( + () -> rpcApiService.getWalletSolidityApi() + .scanShieldedTRC20NotesByIvk(request, responseObserver) + ); + } + + @Override + public void scanShieldedTRC20NotesByOvk(OvkDecryptTRC20Parameters request, + StreamObserver responseObserver) { + walletOnPBFT.futureGet( + () -> rpcApiService.getWalletSolidityApi() + .scanShieldedTRC20NotesByOvk(request, responseObserver) + ); + } + + @Override + public void isShieldedTRC20ContractNoteSpent(NfTRC20Parameters request, + StreamObserver responseObserver) { + walletOnPBFT.futureGet( + () -> rpcApiService.getWalletSolidityApi() + .isShieldedTRC20ContractNoteSpent(request, responseObserver) + ); + } + } } diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/IsShieldedTRC20ContractNoteSpentOnPBFTServlet.java b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/IsShieldedTRC20ContractNoteSpentOnPBFTServlet.java new file mode 100644 index 00000000000..afdb6dfc71e --- /dev/null +++ b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/IsShieldedTRC20ContractNoteSpentOnPBFTServlet.java @@ -0,0 +1,26 @@ +package org.tron.core.services.interfaceOnPBFT.http; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.tron.core.services.http.IsShieldedTRC20ContractNoteSpentServlet; +import org.tron.core.services.interfaceOnPBFT.WalletOnPBFT; + +@Component +@Slf4j(topic = "API") +public class IsShieldedTRC20ContractNoteSpentOnPBFTServlet extends + IsShieldedTRC20ContractNoteSpentServlet { + + @Autowired + private WalletOnPBFT walletOnPBFT; + + protected void doGet(HttpServletRequest request, HttpServletResponse response) { + walletOnPBFT.futureGet(() -> super.doGet(request, response)); + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) { + walletOnPBFT.futureGet(() -> super.doPost(request, response)); + } +} diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/PBFT/HttpApiOnPBFTService.java b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/PBFT/HttpApiOnPBFTService.java index f463d6a06d4..edc86a0d808 100644 --- a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/PBFT/HttpApiOnPBFTService.java +++ b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/PBFT/HttpApiOnPBFTService.java @@ -38,12 +38,15 @@ import org.tron.core.services.interfaceOnPBFT.http.GetPaginatedAssetIssueListOnPBFTServlet; import org.tron.core.services.interfaceOnPBFT.http.GetRewardOnPBFTServlet; import org.tron.core.services.interfaceOnPBFT.http.GetTransactionCountByBlockNumOnPBFTServlet; +import org.tron.core.services.interfaceOnPBFT.http.IsShieldedTRC20ContractNoteSpentOnPBFTServlet; import org.tron.core.services.interfaceOnPBFT.http.IsSpendOnPBFTServlet; import org.tron.core.services.interfaceOnPBFT.http.ListExchangesOnPBFTServlet; import org.tron.core.services.interfaceOnPBFT.http.ListWitnessesOnPBFTServlet; import org.tron.core.services.interfaceOnPBFT.http.ScanAndMarkNoteByIvkOnPBFTServlet; import org.tron.core.services.interfaceOnPBFT.http.ScanNoteByIvkOnPBFTServlet; import org.tron.core.services.interfaceOnPBFT.http.ScanNoteByOvkOnPBFTServlet; +import org.tron.core.services.interfaceOnPBFT.http.ScanShieldedTRC20NotesByIvkOnPBFTServlet; +import org.tron.core.services.interfaceOnPBFT.http.ScanShieldedTRC20NotesByOvkOnPBFTServlet; import org.tron.core.services.interfaceOnPBFT.http.TriggerConstantContractOnPBFTServlet; @Slf4j(topic = "API") @@ -131,6 +134,14 @@ public class HttpApiOnPBFTService implements Service { @Autowired private GetMarketPairListOnPBFTServlet getMarketPairListOnPBFTServlet; + @Autowired + private ScanShieldedTRC20NotesByIvkOnPBFTServlet scanShieldedTRC20NotesByIvkOnPBFTServlet; + @Autowired + private ScanShieldedTRC20NotesByOvkOnPBFTServlet scanShieldedTRC20NotesByOvkOnPBFTServlet; + @Autowired + private IsShieldedTRC20ContractNoteSpentOnPBFTServlet + isShieldedTRC20ContractNoteSpentOnPBFTServlet; + @Override public void init() { @@ -207,6 +218,13 @@ public void start() { context.addServlet(new ServletHolder(getMarketPairListOnPBFTServlet), "/getmarketpairlist"); + context.addServlet(new ServletHolder(scanShieldedTRC20NotesByIvkOnPBFTServlet), + "/scanshieldedtrc20notesbyivk"); + context.addServlet(new ServletHolder(scanShieldedTRC20NotesByOvkOnPBFTServlet), + "/scanshieldedtrc20notesbyovk"); + context.addServlet(new ServletHolder(isShieldedTRC20ContractNoteSpentOnPBFTServlet), + "/isshieldedtrc20contractnotespent"); + int maxHttpConnectNumber = Args.getInstance().getMaxHttpConnectNumber(); if (maxHttpConnectNumber > 0) { server.addBean(new ConnectionLimit(maxHttpConnectNumber, server)); diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/ScanShieldedTRC20NotesByIvkOnPBFTServlet.java b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/ScanShieldedTRC20NotesByIvkOnPBFTServlet.java new file mode 100644 index 00000000000..bf0b70a3a9b --- /dev/null +++ b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/ScanShieldedTRC20NotesByIvkOnPBFTServlet.java @@ -0,0 +1,25 @@ +package org.tron.core.services.interfaceOnPBFT.http; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.tron.core.services.http.ScanShieldedTRC20NotesByIvkServlet; +import org.tron.core.services.interfaceOnPBFT.WalletOnPBFT; + +@Component +@Slf4j(topic = "API") +public class ScanShieldedTRC20NotesByIvkOnPBFTServlet extends ScanShieldedTRC20NotesByIvkServlet { + + @Autowired + private WalletOnPBFT walletOnPBFT; + + protected void doGet(HttpServletRequest request, HttpServletResponse response) { + walletOnPBFT.futureGet(() -> super.doGet(request, response)); + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) { + walletOnPBFT.futureGet(() -> super.doPost(request, response)); + } +} diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/ScanShieldedTRC20NotesByOvkOnPBFTServlet.java b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/ScanShieldedTRC20NotesByOvkOnPBFTServlet.java new file mode 100644 index 00000000000..2bc65ef27c4 --- /dev/null +++ b/framework/src/main/java/org/tron/core/services/interfaceOnPBFT/http/ScanShieldedTRC20NotesByOvkOnPBFTServlet.java @@ -0,0 +1,24 @@ +package org.tron.core.services.interfaceOnPBFT.http; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.tron.core.services.http.ScanShieldedTRC20NotesByOvkServlet; +import org.tron.core.services.interfaceOnPBFT.WalletOnPBFT; + +@Component +@Slf4j(topic = "API") +public class ScanShieldedTRC20NotesByOvkOnPBFTServlet extends ScanShieldedTRC20NotesByOvkServlet { + @Autowired + private WalletOnPBFT walletOnPBFT; + + protected void doGet(HttpServletRequest request, HttpServletResponse response) { + walletOnPBFT.futureGet(() -> super.doGet(request, response)); + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) { + walletOnPBFT.futureGet(() -> super.doPost(request, response)); + } +} From 983cc83a2f047e2e77101f0afd4c49a8ee399a42 Mon Sep 17 00:00:00 2001 From: Timothy <57668523+timothyckw@users.noreply.github.com> Date: Thu, 27 Aug 2020 15:09:20 +0800 Subject: [PATCH 16/60] add testcase in withdrawreward --- .../common/runtime/vm/VMContractTestBase.java | 53 +-- .../common/runtime/vm/WithdrawRewardTest.java | 387 +++++++++++++----- 2 files changed, 321 insertions(+), 119 deletions(-) diff --git a/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java b/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java index 06b2d864ad7..37578a59626 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java @@ -1,6 +1,5 @@ package org.tron.common.runtime.vm; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.junit.After; import org.junit.Before; @@ -8,6 +7,7 @@ import org.tron.common.application.TronApplicationContext; import org.tron.common.runtime.Runtime; import org.tron.common.utils.FileUtil; +import org.tron.consensus.dpos.DposSlot; import org.tron.consensus.dpos.MaintenanceManager; import org.tron.core.ChainBaseManager; import org.tron.core.Constant; @@ -23,35 +23,37 @@ import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol; -@Slf4j -public class VMContractTestBase { +import java.io.File; + @Slf4j + public class VMContractTestBase { - protected String dbPath; - protected Runtime runtime; - protected Manager manager; - protected Repository rootRepository; - protected TronApplicationContext context; - protected ConsensusService consensusService; - protected ChainBaseManager chainBaseManager; - protected MaintenanceManager maintenanceManager; + protected String dbPath; + protected Runtime runtime; + protected Manager manager; + protected Repository rootRepository; + protected TronApplicationContext context; + protected ConsensusService consensusService; + protected ChainBaseManager chainBaseManager; + protected MaintenanceManager maintenanceManager; + protected DposSlot dposSlot; - protected static String OWNER_ADDRESS; - protected static String WITNESS_SR1_ADDRESS; + protected static String OWNER_ADDRESS; + protected static String WITNESS_SR1_ADDRESS; - WitnessStore witnessStore; - DelegationService delegationService; + WitnessStore witnessStore; + DelegationService delegationService; - static { - // 27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1 (test.config) - WITNESS_SR1_ADDRESS = - Constant.ADD_PRE_FIX_STRING_TESTNET + "299F3DB80A24B20A254B89CE639D59132F157F13"; - } + static { + // 27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1 (test.config) + WITNESS_SR1_ADDRESS = + Constant.ADD_PRE_FIX_STRING_TESTNET + "299F3DB80A24B20A254B89CE639D59132F157F13"; + } - @Before - public void init() { - dbPath = "output_" + this.getClass().getName(); - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + @Before + public void init() { + dbPath = "output_" + this.getClass().getName(); + Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); // TRdmP9bYvML7dGUX9Rbw2kZrE2TayPZmZX - 41abd4b9367799eaa3197fecb144eb71de1e049abc OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; @@ -62,6 +64,7 @@ public void init() { rootRepository.commit(); manager = context.getBean(Manager.class); + dposSlot = context.getBean(DposSlot.class); chainBaseManager = manager.getChainBaseManager(); witnessStore = context.getBean(WitnessStore.class); consensusService = context.getBean(ConsensusService.class); diff --git a/framework/src/test/java/org/tron/common/runtime/vm/WithdrawRewardTest.java b/framework/src/test/java/org/tron/common/runtime/vm/WithdrawRewardTest.java index 126ab11a0a5..1c783d27e8e 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/WithdrawRewardTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/WithdrawRewardTest.java @@ -4,6 +4,8 @@ import java.math.BigInteger; import java.util.Arrays; import java.util.Collections; +import java.util.Map; + import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.spongycastle.util.encoders.Hex; @@ -113,23 +115,7 @@ function getContractBAddressTest() public returns (address) { } */ - @Test - public void testWithdrawRewardInLocalContract() - throws ContractExeException, ReceiptCheckErrException, ValidateSignatureException, - BadNumberBlockException, ValidateScheduleException, ContractValidateException, - VMIllegalException, DupTransactionException, TooBigTransactionException, - TooBigTransactionResultException, BadBlockException, NonCommonBlockException, - TransactionExpirationException, UnLinkedBlockException, TaposException, - ZksnarkException, AccountResourceInsufficientException { - ConfigLoader.disable = true; - VMConfig.initAllowTvmTransferTrc10(1); - VMConfig.initAllowTvmConstantinople(1); - VMConfig.initAllowTvmSolidity059(1); - VMConfig.initAllowTvmStake(1); - manager.getDynamicPropertiesStore().saveChangeDelegation(1); - - String contractName = "TestWithdrawReward"; - byte[] address = Hex.decode(OWNER_ADDRESS); + public String getABI() { String abi = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\"," + "\"type\":\"constructor\"},{\"constant\":false," + "\"inputs\":[{\"internalType\":\"address\",\"name\":\"sr\"," @@ -168,6 +154,11 @@ public void testWithdrawRewardInLocalContract() + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," + "\"type\":\"function\"}]"; + + return abi; + } + + public String getFactoryCode() { String factoryCode = "60806040526040516100109061005c565b604051809103906" + "000f08015801561002c573d6000803e3d6000fd5b50600180546001600160a" + "01b03929092166001600160a01b03199283161790556000805490911633179" @@ -207,6 +198,30 @@ public void testWithdrawRewardInLocalContract() + "115158252519081900360200190f35b6000d7905090565b60008183d593925" + "0505056fea26474726f6e5820f52f0d803d46c1926596c7faa3b969812b567" + "66163eb8ca0270d34e3cff1d3b164736f6c634300050d0031"; + + return factoryCode; + } + + @Test + public void testWithdrawRewardInLocalContract() + throws ContractExeException, ReceiptCheckErrException, ValidateSignatureException, + BadNumberBlockException, ValidateScheduleException, ContractValidateException, + VMIllegalException, DupTransactionException, TooBigTransactionException, + TooBigTransactionResultException, BadBlockException, NonCommonBlockException, + TransactionExpirationException, UnLinkedBlockException, TaposException, + ZksnarkException, AccountResourceInsufficientException { + ConfigLoader.disable = true; + VMConfig.initAllowTvmTransferTrc10(1); + VMConfig.initAllowTvmConstantinople(1); + VMConfig.initAllowTvmSolidity059(1); + VMConfig.initAllowTvmStake(1); + manager.getDynamicPropertiesStore().saveChangeDelegation(1); + + String contractName = "TestWithdrawReward"; + byte[] address = Hex.decode(OWNER_ADDRESS); + String abi = getABI(); + String factoryCode = getFactoryCode(); + long value = 1000000000; long fee = 100000000; long consumeUserResourcePercent = 0; @@ -405,83 +420,8 @@ public void testWithdrawRewardInAnotherContract() String contractName = "TestWithdrawRewardWithContract"; byte[] address = Hex.decode(OWNER_ADDRESS); - String abi = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\"," - + "\"type\":\"constructor\"},{\"constant\":false," - + "\"inputs\":[{\"internalType\":\"address\",\"name\":\"sr\"," - + "\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\"," - + "\"type\":\"uint256\"}],\"name\":\"contractBStakeTest\"," - + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," - + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," - + "{\"constant\":false,\"inputs\":[],\"name\":\"contractBWithdrawRewardTest\"," - + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," - + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," - + "\"type\":\"function\"},{\"constant\":false,\"inputs\":[]," - + "\"name\":\"getContractBAddressTest\"," - + "\"outputs\":[{\"internalType\":\"address\",\"name\":\"\"," - + "\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," - + "\"type\":\"function\"},{\"constant\":false,\"inputs\":[]," - + "\"name\":\"localContractAddrTest\",\"outputs\":[{\"internalType\":\"uint256\"," - + "\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false," - + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," - + "\"inputs\":[],\"name\":\"otherContractAddrTest\"," - + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," - + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," - + "\"type\":\"function\"},{\"constant\":false," - + "\"inputs\":[{\"internalType\":\"address\",\"name\":\"addr\"," - + "\"type\":\"address\"}],\"name\":\"rewardBalanceTest\"," - + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," - + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," - + "\"type\":\"function\"},{\"constant\":false," - + "\"inputs\":[{\"internalType\":\"address\",\"name\":\"sr\"," - + "\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\"," - + "\"type\":\"uint256\"}],\"name\":\"stakeTest\"," - + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," - + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," - + "{\"constant\":false,\"inputs\":[],\"name\":\"unstakeTest\",\"outputs\":[]," - + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," - + "{\"constant\":false,\"inputs\":[],\"name\":\"withdrawRewardTest\"," - + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," - + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," - + "\"type\":\"function\"}]"; - String factoryCode = "60806040526040516100109061005c565b604051809103906" - + "000f08015801561002c573d6000803e3d6000fd5b50600180546001600160a" - + "01b03929092166001600160a01b03199283161790556000805490911633179" - + "055610069565b6101108061039c83390190565b61032480610078600039600" - + "0f3fe608060405234801561001057600080fd5b50d3801561001d57600080f" - + "d5b50d2801561002a57600080fd5b50600436106100ad5760003560e01c806" - + "3b3e835e111610080578063b3e835e114610156578063c290120a146101605" - + "78063cb2d51cf14610168578063d30a28ee14610170578063e49de2d014610" - + "178576100ad565b806310198157146100b257806325a26c30146100d657806" - + "38db848f114610116578063a223c65f14610130575b600080fd5b6100ba610" - + "1a4565b604080516001600160a01b039092168252519081900360200190f35" - + "b610102600480360360408110156100ec57600080fd5b506001600160a01b0" - + "381351690602001356101b3565b60408051911515825251908190036020019" - + "0f35b61011e61023f565b60408051918252519081900360200190f35b61011" - + "e6004803603602081101561014657600080fd5b50356001600160a01b03166" - + "102b6565b61015e6102c3565b005b61011e6102c7565b61011e6102cf565b6" - + "1011e6102d4565b6101026004803603604081101561018e57600080fd5b506" - + "001600160a01b0381351690602001356102e4565b6001546001600160a01b0" - + "31690565b60015460408051630e49de2d60e41b81526001600160a01b03858" - + "1166004830152602482018590529151600093929092169163e49de2d091604" - + "48082019260209290919082900301818787803b15801561020c57600080fd5" - + "b505af1158015610220573d6000803e3d6000fd5b505050506040513d60208" - + "1101561023657600080fd5b50519392505050565b600154604080516361480" - + "90560e11b815290516000926001600160a01b03169163c290120a916004808" - + "30192602092919082900301818787803b15801561028557600080fd5b505af" - + "1158015610299573d6000803e3d6000fd5b505050506040513d60208110156" - + "102af57600080fd5b5051905090565b6001600160a01b0316d890565bd6505" - + "65b6000d7905090565b30d890565b6001546001600160a01b0316d890565b6" - + "0008183d5939250505056fea26474726f6e582064d946716e1b0c5f00dcf70" - + "b3ff065ea0587cd3719b2ba94783edeb58413020464736f6c634300050d003" - + "16080604052600080546001600160a01b0319163317905560ec80610024600" - + "0396000f3fe6080604052348015600f57600080fd5b50d38015601b5760008" - + "0fd5b50d28015602757600080fd5b5060043610604a5760003560e01c8063c" - + "290120a14604f578063e49de2d0146067575b600080fd5b605560a4565b604" - + "08051918252519081900360200190f35b609060048036036040811015607b5" - + "7600080fd5b506001600160a01b03813516906020013560ac565b604080519" - + "115158252519081900360200190f35b6000d7905090565b60008183d593925" - + "0505056fea26474726f6e5820f52f0d803d46c1926596c7faa3b969812b567" - + "66163eb8ca0270d34e3cff1d3b164736f6c634300050d0031"; + String abi = getABI(); + String factoryCode = getFactoryCode(); long value = 1000000000; long fee = 100000000; long consumeUserResourcePercent = 0; @@ -752,6 +692,265 @@ public Protocol.Block getBlock(ByteString witness, long time, byte[] privateKey) Protocol.Block signedBlock = block.toBuilder().setBlockHeader(blockHeader).build(); return signedBlock; } + + @Test + public void testWithdrawRewardInLocalContractAfter24Hour() + throws ContractExeException, ReceiptCheckErrException, ValidateSignatureException, + BadNumberBlockException, ValidateScheduleException, ContractValidateException, + VMIllegalException, DupTransactionException, TooBigTransactionException, + TooBigTransactionResultException, BadBlockException, NonCommonBlockException, + TransactionExpirationException, UnLinkedBlockException, TaposException, + ZksnarkException, AccountResourceInsufficientException { + ConfigLoader.disable = true; + VMConfig.initAllowTvmTransferTrc10(1); + VMConfig.initAllowTvmConstantinople(1); + VMConfig.initAllowTvmSolidity059(1); + VMConfig.initAllowTvmStake(1); + manager.getDynamicPropertiesStore().saveChangeDelegation(1); + + String contractName = "TestWithdrawReward"; + byte[] address = Hex.decode(OWNER_ADDRESS); + String abi = getABI(); + String factoryCode = getFactoryCode(); + long value = 1000000000; + long fee = 100000000; + long consumeUserResourcePercent = 0; + + // deploy contract + Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( + contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, + null); + byte[] factoryAddress = WalletUtil.generateContractAddress(trx); + String factoryAddressStr = StringUtil.encode58Check(factoryAddress); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); + Assert.assertNull(runtime.getRuntimeError()); + + // Trigger contract method: stakeTest(address,uint256) + String methodByAddr = "stakeTest(address,uint256)"; + String witness = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; + String hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList(witness, 100000000)); + TVMTestResult result = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); + Assert.assertNull(result.getRuntime().getRuntimeError()); + + byte[] returnValue = result.getRuntime().getResult().getHReturn(); + Assert.assertEquals(Hex.toHexString(returnValue), + "0000000000000000000000000000000000000000000000000000000000000001"); + + // Do Maintenance & Generate New Block + maintenanceManager.doMaintenance(); + String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; + byte[] privateKey = ByteArray.fromHexString(key); + final ECKey ecKey = ECKey.fromPrivate(privateKey); + byte[] witnessAddress = ecKey.getAddress(); + WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(witnessAddress)); + chainBaseManager.addWitness(ByteString.copyFrom(witnessAddress)); + Protocol.Block block = getSignedBlock(witnessCapsule.getAddress(), + System.currentTimeMillis(), privateKey); + manager.pushBlock(new BlockCapsule(block));//cycle: 1 addReward + + // Trigger contract method: rewardBalanceTest(address) + methodByAddr = "rewardBalanceTest(address)"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); + result = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); + Assert.assertNull(result.getRuntime().getRuntimeError()); + + returnValue = result.getRuntime().getResult().getHReturn(); + + Assert.assertEquals(Hex.toHexString(returnValue), + "0000000000000000000000000000000000000000000000000000000000000000"); + + Protocol.Block newBlock = getBlock(witnessCapsule.getAddress(), + System.currentTimeMillis(), privateKey); + BlockCapsule blockCapsule = new BlockCapsule(newBlock); + blockCapsule.generatedByMyself = true; + + // Trigger contract method: withdrawRewardTest() + methodByAddr = "withdrawRewardTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + result = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); + Assert.assertNull(result.getRuntime().getRuntimeError()); + + returnValue = result.getRuntime().getResult().getHReturn(); + Assert.assertEquals(Hex.toHexString(returnValue), + "0000000000000000000000000000000000000000000000000000000000000000"); + + // Execute Next Cycle + maintenanceManager.doMaintenance(); + WitnessCapsule localWitnessCapsule = manager.getWitnessStore() + .get(StringUtil.hexString2ByteString(WITNESS_SR1_ADDRESS).toByteArray()); + Assert.assertEquals(205, localWitnessCapsule.getVoteCount()); + + // Trigger contract method: rewardBalanceTest(address) + methodByAddr = "rewardBalanceTest(address)"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); + result = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); + Assert.assertNull(result.getRuntime().getRuntimeError()); + + returnValue = result.getRuntime().getResult().getHReturn(); + BigInteger reward = new BigInteger(Hex.toHexString(returnValue), 16); + + // Current Reward: Total Reward * Vote Rate + // BigInteger reward = new BigInteger(Hex.toHexString(returnValue), 16); + // byte[] sr1 = decodeFromBase58Check(witness); + // long totalReward = (long) ((double) rootRepository + // .getDelegationStore().getReward(1, sr1)); + // long totalVote = rootRepository.getDelegationStore().getWitnessVote(1, sr1); + // double voteRate = (double) 100 / totalVote; + // long curReward = (long) (totalReward * voteRate); + // Assert.assertEquals(reward.longValue(), curReward); + + //total reward: block reward + vote reward + long blockReward = 25600000; + long voteReward = 2186667; + long totalReward = blockReward + voteReward; + double voteRate = (double) 100 / 205; + long curReward = (long) (totalReward * voteRate); + Assert.assertEquals(reward.longValue(), curReward); + + // Trigger contract method: localContractAddrTest() + methodByAddr = "localContractAddrTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + result = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); + Assert.assertNull(result.getRuntime().getRuntimeError()); + + returnValue = result.getRuntime().getResult().getHReturn(); + + Assert.assertEquals((new BigInteger(Hex.toHexString(returnValue), 16)).longValue(), curReward); + + // Trigger contract method: withdrawRewardTest() + methodByAddr = "withdrawRewardTest()"; + + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + result = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); + Assert.assertNull(result.getRuntime().getRuntimeError()); + + returnValue = result.getRuntime().getResult().getHReturn(); + + Assert.assertEquals((new BigInteger(Hex.toHexString(returnValue), 16)).longValue(), curReward); + + // Trigger contract method: rewardBalanceTest(address) + methodByAddr = "rewardBalanceTest(address)"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); + result = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); + Assert.assertNull(result.getRuntime().getRuntimeError()); + + returnValue = result.getRuntime().getResult().getHReturn(); + + Assert.assertEquals(Hex.toHexString(returnValue), + "0000000000000000000000000000000000000000000000000000000000000000"); + + // Trigger contract method: withdrawRewardTest() + methodByAddr = "withdrawRewardTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + result = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); + Assert.assertNull(result.getRuntime().getRuntimeError()); + + returnValue = result.getRuntime().getResult().getHReturn(); + Assert.assertEquals(Hex.toHexString(returnValue), + "0000000000000000000000000000000000000000000000000000000000000000"); + + // Within 24 Hours + long num = chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber(); + ByteString latestHeadHash = + chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderHash().getByteString(); + blockCapsule = + createTestBlockCapsule( + System.currentTimeMillis() + 80400000, + num + 1, + latestHeadHash); + manager.pushBlock(blockCapsule); + + // long currentTime = System.currentTimeMillis(); + // for (int i = 0; i < (86400 / 3 - 3); i++) { + // currentTime += 3000; + // ByteString latestHeadHash = chainBaseManager.getDynamicPropertiesStore() + // .getLatestBlockHeaderHash().getByteString(); + // blockCapsule = + // createTestBlockCapsule( + // currentTime, + // ++num, + // latestHeadHash, + // privateKey); + // manager.pushBlock(blockCapsule); + // } + + // Trigger contract method: withdrawRewardTest() + methodByAddr = "withdrawRewardTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + result = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); + Assert.assertNull(result.getRuntime().getRuntimeError()); + + returnValue = result.getRuntime().getResult().getHReturn(); + Assert.assertEquals(Hex.toHexString(returnValue), + "0000000000000000000000000000000000000000000000000000000000000000"); + + // After 24 Hours + num = chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber(); + latestHeadHash = + chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderHash().getByteString(); + blockCapsule = + createTestBlockCapsule( + System.currentTimeMillis() + 86400000 + 3000, + num + 1, + latestHeadHash); + manager.pushBlock(blockCapsule); + // for (int i = 0; i < 3; i++) { + // currentTime += 3000; + // ByteString latestHeadHash = chainBaseManager.getDynamicPropertiesStore() + // .getLatestBlockHeaderHash().getByteString(); + // blockCapsule = + // createTestBlockCapsule( + // currentTime, + // ++num, + // latestHeadHash, + // privateKey); + // manager.pushBlock(blockCapsule); + // } + + // Trigger contract method: withdrawRewardTest() + methodByAddr = "withdrawRewardTest()"; + hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); + result = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); + Assert.assertNull(result.getRuntime().getRuntimeError()); + + returnValue = result.getRuntime().getResult().getHReturn(); + Assert.assertNotEquals(Hex.toHexString(returnValue), + "0000000000000000000000000000000000000000000000000000000000000000"); + + ConfigLoader.disable = false; + } + + private BlockCapsule createTestBlockCapsule(long time, + long number, ByteString hash) { + ByteString witnessAddress = dposSlot.getScheduledWitness(dposSlot.getSlot(time)); + BlockCapsule blockCapsule = new BlockCapsule(number, Sha256Hash.wrap(hash), time, + witnessAddress); + blockCapsule.generatedByMyself = true; + blockCapsule.setMerkleRoot(); + //blockCapsule.sign(privateKey); + //blockCapsule.sign(ByteArray.fromHexString(privateKey.get(witnessAddress))); + return blockCapsule; + } } From ca22f2f1adb896ab38b7f762a4bfe37b7e595426 Mon Sep 17 00:00:00 2001 From: Timothy <57668523+timothyckw@users.noreply.github.com> Date: Mon, 31 Aug 2020 15:02:51 +0800 Subject: [PATCH 17/60] fix check style --- .../common/runtime/vm/VMContractTestBase.java | 53 +++++++++---------- 1 file changed, 26 insertions(+), 27 deletions(-) diff --git a/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java b/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java index 37578a59626..0f05b89d8c0 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java @@ -1,5 +1,6 @@ package org.tron.common.runtime.vm; +import java.io.File; import lombok.extern.slf4j.Slf4j; import org.junit.After; import org.junit.Before; @@ -23,37 +24,35 @@ import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol; -import java.io.File; - @Slf4j - public class VMContractTestBase { - - protected String dbPath; - protected Runtime runtime; - protected Manager manager; - protected Repository rootRepository; - protected TronApplicationContext context; - protected ConsensusService consensusService; - protected ChainBaseManager chainBaseManager; - protected MaintenanceManager maintenanceManager; - protected DposSlot dposSlot; +@Slf4j +public class VMContractTestBase { + protected String dbPath; + protected Runtime runtime; + protected Manager manager; + protected Repository rootRepository; + protected TronApplicationContext context; + protected ConsensusService consensusService; + protected ChainBaseManager chainBaseManager; + protected MaintenanceManager maintenanceManager; + protected DposSlot dposSlot; - protected static String OWNER_ADDRESS; - protected static String WITNESS_SR1_ADDRESS; + protected static String OWNER_ADDRESS; + protected static String WITNESS_SR1_ADDRESS; - WitnessStore witnessStore; - DelegationService delegationService; + WitnessStore witnessStore; + DelegationService delegationService; - static { - // 27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1 (test.config) - WITNESS_SR1_ADDRESS = - Constant.ADD_PRE_FIX_STRING_TESTNET + "299F3DB80A24B20A254B89CE639D59132F157F13"; - } + static { + // 27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1 (test.config) + WITNESS_SR1_ADDRESS = + Constant.ADD_PRE_FIX_STRING_TESTNET + "299F3DB80A24B20A254B89CE639D59132F157F13"; + } - @Before - public void init() { - dbPath = "output_" + this.getClass().getName(); - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + @Before + public void init() { + dbPath = "output_" + this.getClass().getName(); + Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); // TRdmP9bYvML7dGUX9Rbw2kZrE2TayPZmZX - 41abd4b9367799eaa3197fecb144eb71de1e049abc OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; From 073948e8203fbfd89b5ced68e7edda9a0a7439a8 Mon Sep 17 00:00:00 2001 From: xiangdepeng Date: Mon, 31 Aug 2020 16:29:57 +0800 Subject: [PATCH 18/60] add log to stake --- .../java/org/tron/core/vm/nativecontract/StakeProcessor.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/StakeProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/StakeProcessor.java index a925df834b5..a413fb5c5cf 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/StakeProcessor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/StakeProcessor.java @@ -33,6 +33,8 @@ public void process(StakeParam stakeParam, Repository repository) long frozenDuration = repository.getDynamicPropertiesStore().getMinFrozenTime(); validateFreeze(stakeParam.getOwnerAddress(), frozenDuration, freezeBalance, repository); executeFreeze(stakeParam.getOwnerAddress(), frozenDuration, freezeBalance, stakeParam.getNow(), repository); + } else { + logger.info("no need to freeze for stake"); } long voteCount = stakeParam.getStakeAmount() / ChainConstant.TRX_PRECISION; Protocol.Vote vote = Protocol.Vote.newBuilder() From d5d784c5be869cb93b211b6ca9e712d9f00928dd Mon Sep 17 00:00:00 2001 From: neo hong Date: Mon, 31 Aug 2020 17:15:07 +0800 Subject: [PATCH 19/60] checkstyle and try catch arithmeticException --- .../ContractProcessorConstant.java | 16 +- .../vm/nativecontract/ContractService.java | 239 +++++++++--------- .../nativecontract/TokenIssueProcessor.java | 139 +++++----- .../nativecontract/UpdateAssetProcessor.java | 89 +++---- .../WithdrawRewardProcessor.java | 142 +++++------ .../org/tron/core/vm/program/Program.java | 11 +- .../org/tron/common/runtime/vm/Trc10Test.java | 20 +- 7 files changed, 333 insertions(+), 323 deletions(-) diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/ContractProcessorConstant.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/ContractProcessorConstant.java index 06c10268530..5a434b703ad 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/ContractProcessorConstant.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/ContractProcessorConstant.java @@ -2,19 +2,19 @@ public class ContractProcessorConstant { - public static final String ACCOUNT_EXCEPTION_STR = "Account["; + public static final String ACCOUNT_EXCEPTION_STR = "Account["; - public static final String WITNESS_EXCEPTION_STR = "Witness["; + public static final String WITNESS_EXCEPTION_STR = "Witness["; - public static final String NOT_EXIST_STR = "] not exists"; + public static final String NOT_EXIST_STR = "] not exists"; - public static final String CONTRACT_NULL = "contract is null"; + public static final String CONTRACT_NULL = "contract is null"; - public static final String CONTRACT_NOT_EXIST = "No contract!"; + public static final String CONTRACT_NOT_EXIST = "No contract!"; - public static final String STORE_NOT_EXIST = "No account store or dynamic store!"; + public static final String STORE_NOT_EXIST = "No account store or dynamic store!"; - public static final String TRX = "trx"; + public static final String TRX = "trx"; - public static final int TOKEN_ISSUE_PRECISION = 6; + public static final int TOKEN_ISSUE_PRECISION = 6; } diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/ContractService.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/ContractService.java index 30f4a0d7881..91ba580d58e 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/ContractService.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/ContractService.java @@ -10,136 +10,139 @@ @Slf4j(topic = "contractService") public class ContractService { - private ContractService(){} + private ContractService() { + } - public static ContractService getInstance(){ - return ContractService.Singleton.INSTANCE.getInstance(); + public static ContractService getInstance() { + return ContractService.Singleton.INSTANCE.getInstance(); + } + + private enum Singleton { + INSTANCE; + private ContractService instance; + + Singleton() { + instance = new ContractService(); } - private enum Singleton { - INSTANCE; - private ContractService instance; - Singleton() { - instance = new ContractService(); - } - public ContractService getInstance() { - return instance; - } + public ContractService getInstance() { + return instance; } + } - public void withdrawReward(byte[] address, Repository repository) { - if (!repository.getDynamicPropertiesStore().allowChangeDelegation()) { - return; - } - AccountCapsule accountCapsule = repository.getAccount(address); - long beginCycle = repository.getBeginCycle(address); - long endCycle = repository.getEndCycle(address); - long currentCycle = repository.getDynamicPropertiesStore().getCurrentCycleNumber(); - long reward = 0; - if (beginCycle > currentCycle || accountCapsule == null) { - return; - } - if (beginCycle == currentCycle) { - AccountCapsule account = repository.getAccountVote(beginCycle, address); - if (account != null) { - return; - } - } - //withdraw the latest cycle reward - if (beginCycle + 1 == endCycle && beginCycle < currentCycle) { - AccountCapsule account = repository.getAccountVote(beginCycle, address); - if (account != null) { - reward = computeReward(beginCycle, account, repository); - adjustAllowance(address, reward, repository); - reward = 0; - logger.info("latest cycle reward {},{}", beginCycle, account.getVotesList()); - } - beginCycle += 1; - } - endCycle = currentCycle; - if (CollectionUtils.isEmpty(accountCapsule.getVotesList())) { - repository.updateRemark(address, endCycle); - repository.updateBeginCycle(address, endCycle + 1); - return; - } - if (beginCycle < endCycle) { - for (long cycle = beginCycle; cycle < endCycle; cycle++) { - reward += computeReward(cycle, accountCapsule, repository); - } - adjustAllowance(address, reward, repository); + public void withdrawReward(byte[] address, Repository repository) { + if (!repository.getDynamicPropertiesStore().allowChangeDelegation()) { + return; + } + AccountCapsule accountCapsule = repository.getAccount(address); + long beginCycle = repository.getBeginCycle(address); + long endCycle = repository.getEndCycle(address); + long currentCycle = repository.getDynamicPropertiesStore().getCurrentCycleNumber(); + long reward = 0; + if (beginCycle > currentCycle || accountCapsule == null) { + return; + } + if (beginCycle == currentCycle) { + AccountCapsule account = repository.getAccountVote(beginCycle, address); + if (account != null) { + return; + } + } + //withdraw the latest cycle reward + if (beginCycle + 1 == endCycle && beginCycle < currentCycle) { + AccountCapsule account = repository.getAccountVote(beginCycle, address); + if (account != null) { + reward = computeReward(beginCycle, account, repository); + adjustAllowance(address, reward, repository); + reward = 0; + logger.info("latest cycle reward {},{}", beginCycle, account.getVotesList()); + } + beginCycle += 1; + } + endCycle = currentCycle; + if (CollectionUtils.isEmpty(accountCapsule.getVotesList())) { + repository.updateRemark(address, endCycle); + repository.updateBeginCycle(address, endCycle + 1); + return; + } + if (beginCycle < endCycle) { + for (long cycle = beginCycle; cycle < endCycle; cycle++) { + reward += computeReward(cycle, accountCapsule, repository); + } + adjustAllowance(address, reward, repository); - } - repository.updateBeginCycle(address, endCycle); - repository.updateEndCycle(address, endCycle + 1); - repository.updateAccountVote(address,endCycle, accountCapsule); - logger.info("adjust {} allowance {}, now currentCycle {}, beginCycle {}, endCycle {}, " - + "account vote {},", Hex.toHexString(address), reward, currentCycle, - beginCycle, endCycle, accountCapsule.getVotesList()); } + repository.updateBeginCycle(address, endCycle); + repository.updateEndCycle(address, endCycle + 1); + repository.updateAccountVote(address, endCycle, accountCapsule); + logger.info("adjust {} allowance {}, now currentCycle {}, beginCycle {}, endCycle {}, " + + "account vote {},", Hex.toHexString(address), reward, currentCycle, + beginCycle, endCycle, accountCapsule.getVotesList()); + } - private long computeReward(long cycle, AccountCapsule accountCapsule, Repository repository) { - long reward = 0; + private long computeReward(long cycle, AccountCapsule accountCapsule, Repository repository) { + long reward = 0; - for (Protocol.Vote vote : accountCapsule.getVotesList()) { - byte[] srAddress = vote.getVoteAddress().toByteArray(); - long totalReward = repository.getDelegationStore().getReward(cycle, - srAddress); - long totalVote = repository.getDelegationStore().getWitnessVote(cycle, srAddress); - if (totalVote == DelegationStore.REMARK || totalVote == 0) { - continue; - } - long userVote = vote.getVoteCount(); - double voteRate = (double) userVote / totalVote; - reward += voteRate * totalReward; - logger.debug("computeReward {} {} {} {},{},{},{}", cycle, - Hex.toHexString(accountCapsule.getAddress().toByteArray()), Hex.toHexString(srAddress), - userVote, totalVote, totalReward, reward); - } - return reward; + for (Protocol.Vote vote : accountCapsule.getVotesList()) { + byte[] srAddress = vote.getVoteAddress().toByteArray(); + long totalReward = repository.getDelegationStore().getReward(cycle, + srAddress); + long totalVote = repository.getDelegationStore().getWitnessVote(cycle, srAddress); + if (totalVote == DelegationStore.REMARK || totalVote == 0) { + continue; + } + long userVote = vote.getVoteCount(); + double voteRate = (double) userVote / totalVote; + reward += voteRate * totalReward; + logger.debug("computeReward {} {} {} {},{},{},{}", cycle, + Hex.toHexString(accountCapsule.getAddress().toByteArray()), Hex.toHexString(srAddress), + userVote, totalVote, totalReward, reward); } + return reward; + } - public void adjustAllowance(byte[] address, long amount, Repository repository) { - if (amount <= 0) { - return; - } - AccountCapsule accountCapsule = repository.getAccount(address); - long allowance = accountCapsule.getAllowance(); - accountCapsule.setAllowance(allowance + amount); - repository.putAccountValue(accountCapsule.createDbKey(), accountCapsule); + public void adjustAllowance(byte[] address, long amount, Repository repository) { + if (amount <= 0) { + return; } + AccountCapsule accountCapsule = repository.getAccount(address); + long allowance = accountCapsule.getAllowance(); + accountCapsule.setAllowance(allowance + amount); + repository.putAccountValue(accountCapsule.createDbKey(), accountCapsule); + } - public long queryReward(byte[] address, Repository repository) { - if (!repository.getDynamicPropertiesStore().allowChangeDelegation()) { - return 0; - } - AccountCapsule accountCapsule = repository.getAccount(address); - long beginCycle = repository.getBeginCycle(address); - long endCycle = repository.getEndCycle(address); - long currentCycle = repository.getDynamicPropertiesStore().getCurrentCycleNumber(); - long reward = 0; - if (accountCapsule == null) { - return 0; - } - if (beginCycle > currentCycle) { - return accountCapsule.getAllowance(); - } - //withdraw the latest cycle reward - if (beginCycle + 1 == endCycle && beginCycle < currentCycle) { - AccountCapsule account = repository.getAccountVote(beginCycle, address); - if (account != null) { - reward = computeReward(beginCycle, account, repository); - } - beginCycle += 1; - } - endCycle = currentCycle; - if (CollectionUtils.isEmpty(accountCapsule.getVotesList())) { - return reward + accountCapsule.getAllowance(); - } - if (beginCycle < endCycle) { - for (long cycle = beginCycle; cycle < endCycle; cycle++) { - reward += computeReward(cycle, accountCapsule, repository); - } - } - return reward + accountCapsule.getAllowance(); + public long queryReward(byte[] address, Repository repository) { + if (!repository.getDynamicPropertiesStore().allowChangeDelegation()) { + return 0; + } + AccountCapsule accountCapsule = repository.getAccount(address); + long beginCycle = repository.getBeginCycle(address); + long endCycle = repository.getEndCycle(address); + long currentCycle = repository.getDynamicPropertiesStore().getCurrentCycleNumber(); + long reward = 0; + if (accountCapsule == null) { + return 0; + } + if (beginCycle > currentCycle) { + return accountCapsule.getAllowance(); + } + //withdraw the latest cycle reward + if (beginCycle + 1 == endCycle && beginCycle < currentCycle) { + AccountCapsule account = repository.getAccountVote(beginCycle, address); + if (account != null) { + reward = computeReward(beginCycle, account, repository); + } + beginCycle += 1; + } + endCycle = currentCycle; + if (CollectionUtils.isEmpty(accountCapsule.getVotesList())) { + return reward + accountCapsule.getAllowance(); + } + if (beginCycle < endCycle) { + for (long cycle = beginCycle; cycle < endCycle; cycle++) { + reward += computeReward(cycle, accountCapsule, repository); + } } + return reward + accountCapsule.getAllowance(); + } } diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/TokenIssueProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/TokenIssueProcessor.java index a5ed5fbc140..0e52825feff 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/TokenIssueProcessor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/TokenIssueProcessor.java @@ -1,5 +1,7 @@ package org.tron.core.vm.nativecontract; +import java.util.Objects; +import lombok.extern.slf4j.Slf4j; import org.tron.common.utils.ByteArray; import org.tron.common.utils.DecodeUtil; import org.tron.core.capsule.AccountCapsule; @@ -9,78 +11,79 @@ import org.tron.core.vm.nativecontract.param.TokenIssueParam; import org.tron.core.vm.repository.Repository; -import java.util.Objects; - import static org.tron.core.vm.nativecontract.ContractProcessorConstant.*; +@Slf4j(topic = "Processor") public class TokenIssueProcessor { - public void execute(Object contract, Repository repository) { - TokenIssueParam tokenIssueParam = (TokenIssueParam) contract; - long tokenIdNum = repository.getTokenIdNum(); - tokenIdNum++; - repository.saveTokenIdNum(tokenIdNum); - AssetIssueCapsule assetIssueCapsule = new AssetIssueCapsule(tokenIssueParam.getOwnerAddress(), - Long.toString(tokenIdNum), ByteArray.toStr(tokenIssueParam.getName()), - ByteArray.toStr(tokenIssueParam.getAbbr()), tokenIssueParam.getTotalSupply(), - tokenIssueParam.getPrecision()); - repository.putAssetIssueValue(assetIssueCapsule.createDbV2Key(), assetIssueCapsule); - AccountCapsule accountCapsule = repository.getAccount(tokenIssueParam.getOwnerAddress()); - accountCapsule.setAssetIssuedName(assetIssueCapsule.getName().toByteArray()); - accountCapsule.setAssetIssuedID(ByteArray.fromString(assetIssueCapsule.getId())); - accountCapsule - .addAssetV2(assetIssueCapsule.createDbV2Key(), tokenIssueParam.getTotalSupply()); - accountCapsule.setInstance(accountCapsule.getInstance().toBuilder().build()); - // spend 1024trx for assetissue, send to blackhole address - AccountCapsule bhAccountCapsule = repository.getAccount(repository.getBlackHoleAddress()); - bhAccountCapsule.setBalance(Math.addExact(bhAccountCapsule.getBalance(), - repository.getDynamicPropertiesStore().getAssetIssueFee())); - accountCapsule.setBalance(Math.subtractExact(accountCapsule.getBalance(), - repository.getDynamicPropertiesStore().getAssetIssueFee())); - repository.putAccountValue(tokenIssueParam.getOwnerAddress(), accountCapsule); - repository.putAccountValue(bhAccountCapsule.getAddress().toByteArray(), bhAccountCapsule); - } + public void execute(Object contract, Repository repository) { + TokenIssueParam tokenIssueParam = (TokenIssueParam) contract; + long tokenIdNum = repository.getTokenIdNum(); + tokenIdNum++; + repository.saveTokenIdNum(tokenIdNum); + AssetIssueCapsule assetIssueCapsule = new AssetIssueCapsule(tokenIssueParam.getOwnerAddress(), + Long.toString(tokenIdNum), ByteArray.toStr(tokenIssueParam.getName()), + ByteArray.toStr(tokenIssueParam.getAbbr()), tokenIssueParam.getTotalSupply(), + tokenIssueParam.getPrecision()); + repository.putAssetIssueValue(assetIssueCapsule.createDbV2Key(), assetIssueCapsule); + AccountCapsule accountCapsule = repository.getAccount(tokenIssueParam.getOwnerAddress()); + accountCapsule.setAssetIssuedName(assetIssueCapsule.getName().toByteArray()); + accountCapsule.setAssetIssuedID(ByteArray.fromString(assetIssueCapsule.getId())); + accountCapsule + .addAssetV2(assetIssueCapsule.createDbV2Key(), tokenIssueParam.getTotalSupply()); + accountCapsule.setInstance(accountCapsule.getInstance().toBuilder().build()); + // spend 1024trx for assetissue, send to blackhole address + AccountCapsule bhAccountCapsule = repository.getAccount(repository.getBlackHoleAddress()); + bhAccountCapsule.setBalance(Math.addExact(bhAccountCapsule.getBalance(), + repository.getDynamicPropertiesStore().getAssetIssueFee())); + accountCapsule.setBalance(Math.subtractExact(accountCapsule.getBalance(), + repository.getDynamicPropertiesStore().getAssetIssueFee())); + repository.putAccountValue(tokenIssueParam.getOwnerAddress(), accountCapsule); + repository.putAccountValue(bhAccountCapsule.getAddress().toByteArray(), bhAccountCapsule); + } - public void validate(Object contract, Repository repository) throws ContractValidateException { - if (Objects.isNull(contract)) { - throw new ContractValidateException(CONTRACT_NULL); - } - if (repository == null) { - throw new ContractValidateException(STORE_NOT_EXIST); - } - if (!(contract instanceof TokenIssueParam)) { - throw new ContractValidateException( - "contract type error,expected type [TokenIssuedContract],real type[" + contract - .getClass() + "]"); - } - TokenIssueParam tokenIssueParam = (TokenIssueParam) contract; - if (!DecodeUtil.addressValid(tokenIssueParam.getOwnerAddress())) { - throw new ContractValidateException("Invalid ownerAddress"); - } - if (!TransactionUtil.validAssetName(tokenIssueParam.getName())) { - throw new ContractValidateException("Invalid assetName"); - } - if ((TRX.equalsIgnoreCase(ByteArray.toStr(tokenIssueParam.getName())))) { - throw new ContractValidateException("assetName can't be trx or null"); - } - if (tokenIssueParam.getPrecision() < 0 || tokenIssueParam.getPrecision() > TOKEN_ISSUE_PRECISION) { - throw new ContractValidateException("precision cannot exceed 6"); - } - if (Objects.nonNull(tokenIssueParam.getAbbr()) && !TransactionUtil.validAssetName(tokenIssueParam.getAbbr())) { - throw new ContractValidateException("Invalid abbreviation for token"); - } - if (tokenIssueParam.getTotalSupply() <= 0) { - throw new ContractValidateException("TotalSupply must greater than 0!"); - } - AccountCapsule accountCapsule = repository.getAccount(tokenIssueParam.getOwnerAddress()); - if (accountCapsule == null) { - throw new ContractValidateException("Account not exists"); - } - if (!accountCapsule.getAssetIssuedName().isEmpty()) { - throw new ContractValidateException("An account can only issue one asset"); - } - if (accountCapsule.getBalance() < repository.getDynamicPropertiesStore().getAssetIssueFee()) { - throw new ContractValidateException("No enough balance for fee!"); - } + public void validate(Object contract, Repository repository) throws ContractValidateException { + if (Objects.isNull(contract)) { + throw new ContractValidateException(CONTRACT_NULL); + } + if (repository == null) { + throw new ContractValidateException(STORE_NOT_EXIST); + } + if (!(contract instanceof TokenIssueParam)) { + throw new ContractValidateException( + "contract type error,expected type [TokenIssuedContract],real type[" + contract + .getClass() + "]"); + } + TokenIssueParam tokenIssueParam = (TokenIssueParam) contract; + if (!DecodeUtil.addressValid(tokenIssueParam.getOwnerAddress())) { + throw new ContractValidateException("Invalid ownerAddress"); + } + if (!TransactionUtil.validAssetName(tokenIssueParam.getName())) { + throw new ContractValidateException("Invalid assetName"); + } + if ((TRX.equalsIgnoreCase(ByteArray.toStr(tokenIssueParam.getName())))) { + throw new ContractValidateException("assetName can't be trx or null"); + } + if (tokenIssueParam.getPrecision() < 0 + || tokenIssueParam.getPrecision() > TOKEN_ISSUE_PRECISION) { + throw new ContractValidateException("precision cannot exceed 6"); + } + if (Objects.nonNull(tokenIssueParam.getAbbr()) + && !TransactionUtil.validAssetName(tokenIssueParam.getAbbr())) { + throw new ContractValidateException("Invalid abbreviation for token"); + } + if (tokenIssueParam.getTotalSupply() <= 0) { + throw new ContractValidateException("TotalSupply must greater than 0!"); + } + AccountCapsule accountCapsule = repository.getAccount(tokenIssueParam.getOwnerAddress()); + if (accountCapsule == null) { + throw new ContractValidateException("Account not exists"); + } + if (!accountCapsule.getAssetIssuedName().isEmpty()) { + throw new ContractValidateException("An account can only issue one asset"); + } + if (accountCapsule.getBalance() < repository.getDynamicPropertiesStore().getAssetIssueFee()) { + throw new ContractValidateException("No enough balance for fee!"); } + } } diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/UpdateAssetProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/UpdateAssetProcessor.java index 099c8ebd4cd..e15296bd94e 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/UpdateAssetProcessor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/UpdateAssetProcessor.java @@ -1,6 +1,8 @@ package org.tron.core.vm.nativecontract; import com.google.protobuf.ByteString; +import java.util.Objects; +import lombok.extern.slf4j.Slf4j; import org.tron.common.utils.DecodeUtil; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; @@ -9,56 +11,55 @@ import org.tron.core.vm.nativecontract.param.UpdateAssetParam; import org.tron.core.vm.repository.Repository; -import java.util.Objects; - import static org.tron.core.vm.nativecontract.ContractProcessorConstant.CONTRACT_NULL; +@Slf4j(topic = "Processor") public class UpdateAssetProcessor { - public void execute(Object contract, Repository repository) { - UpdateAssetParam updateAssetParam = (UpdateAssetParam) contract; - AccountCapsule accountCapsule = repository.getAccount(updateAssetParam.getOwnerAddress()); + public void execute(Object contract, Repository repository) { + UpdateAssetParam updateAssetParam = (UpdateAssetParam) contract; + AccountCapsule accountCapsule = repository.getAccount(updateAssetParam.getOwnerAddress()); - AssetIssueCapsule assetIssueCapsuleV2; - assetIssueCapsuleV2 = repository.getAssetIssue(accountCapsule.getAssetIssuedID().toByteArray()); - assetIssueCapsuleV2.setUrl(ByteString.copyFrom(updateAssetParam.getNewUrl())); - assetIssueCapsuleV2.setDescription(ByteString.copyFrom(updateAssetParam.getNewDesc())); + AssetIssueCapsule assetIssueCapsuleV2; + assetIssueCapsuleV2 = repository.getAssetIssue(accountCapsule.getAssetIssuedID().toByteArray()); + assetIssueCapsuleV2.setUrl(ByteString.copyFrom(updateAssetParam.getNewUrl())); + assetIssueCapsuleV2.setDescription(ByteString.copyFrom(updateAssetParam.getNewDesc())); - repository.putAssetIssueValue(assetIssueCapsuleV2.createDbV2Key(), assetIssueCapsuleV2); - } + repository.putAssetIssueValue(assetIssueCapsuleV2.createDbV2Key(), assetIssueCapsuleV2); + } - public void validate(Object contract, Repository repository) throws ContractValidateException { - if (Objects.isNull(contract)) { - throw new ContractValidateException(CONTRACT_NULL); - } - if (repository == null) { - throw new ContractValidateException(ContractProcessorConstant.STORE_NOT_EXIST); - } - if (!(contract instanceof UpdateAssetParam)) { - throw new ContractValidateException( - "contract type error,expected type [TokenIssuedContract],real type[" + contract - .getClass() + "]"); - } - UpdateAssetParam updateAssetParam = (UpdateAssetParam) contract; - if (!DecodeUtil.addressValid(updateAssetParam.getOwnerAddress())) { - throw new ContractValidateException("Invalid ownerAddress"); - } - AccountCapsule account = repository.getAccount(updateAssetParam.getOwnerAddress()); - if (account == null) { - throw new ContractValidateException("Account does not exist"); - } - if (account.getAssetIssuedID().isEmpty()) { - throw new ContractValidateException("Account has not issued any asset"); - } - if (repository.getAssetIssue(account.getAssetIssuedID().toByteArray()) - == null) { - throw new ContractValidateException("Asset is not existed in AssetIssueV2Store"); - } - if (!TransactionUtil.validUrl(updateAssetParam.getNewUrl())) { - throw new ContractValidateException("Invalid url"); - } - if (!TransactionUtil.validAssetDescription(updateAssetParam.getNewDesc())) { - throw new ContractValidateException("Invalid description"); - } + public void validate(Object contract, Repository repository) throws ContractValidateException { + if (Objects.isNull(contract)) { + throw new ContractValidateException(CONTRACT_NULL); + } + if (repository == null) { + throw new ContractValidateException(ContractProcessorConstant.STORE_NOT_EXIST); + } + if (!(contract instanceof UpdateAssetParam)) { + throw new ContractValidateException( + "contract type error,expected type [TokenIssuedContract],real type[" + contract + .getClass() + "]"); + } + UpdateAssetParam updateAssetParam = (UpdateAssetParam) contract; + if (!DecodeUtil.addressValid(updateAssetParam.getOwnerAddress())) { + throw new ContractValidateException("Invalid ownerAddress"); + } + AccountCapsule account = repository.getAccount(updateAssetParam.getOwnerAddress()); + if (account == null) { + throw new ContractValidateException("Account does not exist"); + } + if (account.getAssetIssuedID().isEmpty()) { + throw new ContractValidateException("Account has not issued any asset"); + } + if (repository.getAssetIssue(account.getAssetIssuedID().toByteArray()) + == null) { + throw new ContractValidateException("Asset is not existed in AssetIssueV2Store"); + } + if (!TransactionUtil.validUrl(updateAssetParam.getNewUrl())) { + throw new ContractValidateException("Invalid url"); + } + if (!TransactionUtil.validAssetDescription(updateAssetParam.getNewDesc())) { + throw new ContractValidateException("Invalid description"); } + } } diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawRewardProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawRewardProcessor.java index 7d5173dc5cc..c99ed6412e9 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawRewardProcessor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawRewardProcessor.java @@ -1,6 +1,8 @@ package org.tron.core.vm.nativecontract; import com.google.common.math.LongMath; +import java.util.Arrays; +import java.util.Objects; import lombok.extern.slf4j.Slf4j; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.DecodeUtil; @@ -11,9 +13,6 @@ import org.tron.core.vm.nativecontract.param.WithdrawRewardParam; import org.tron.core.vm.repository.Repository; -import java.util.Arrays; -import java.util.Objects; - import static org.tron.core.config.Parameter.ChainConstant.FROZEN_PERIOD; import static org.tron.core.vm.nativecontract.ContractProcessorConstant.ACCOUNT_EXCEPTION_STR; import static org.tron.core.vm.nativecontract.ContractProcessorConstant.CONTRACT_NULL; @@ -21,82 +20,83 @@ @Slf4j(topic = "Processor") public class WithdrawRewardProcessor { - public long execute(Object contract, Repository repository, long now) { - WithdrawRewardParam withdrawRewardParam = (WithdrawRewardParam) contract; - byte[] targetAddress = withdrawRewardParam.getTargetAddress(); + public long execute(Object contract, Repository repository, long now) { + WithdrawRewardParam withdrawRewardParam = (WithdrawRewardParam) contract; + byte[] targetAddress = withdrawRewardParam.getTargetAddress(); - ContractService contractService = ContractService.getInstance(); - contractService.withdrawReward(targetAddress,repository); + ContractService contractService = ContractService.getInstance(); + contractService.withdrawReward(targetAddress, repository); - AccountCapsule accountCapsule = repository.getAccount(targetAddress); - repository.updateLastWithdrawCycle(targetAddress, repository.getDynamicPropertiesStore().getCurrentCycleNumber() - ); + AccountCapsule accountCapsule = repository.getAccount(targetAddress); + repository.updateLastWithdrawCycle(targetAddress, + repository.getDynamicPropertiesStore().getCurrentCycleNumber() + ); - long oldBalance = accountCapsule.getBalance(); - long allowance = accountCapsule.getAllowance(); + long oldBalance = accountCapsule.getBalance(); + long allowance = accountCapsule.getAllowance(); - accountCapsule.setInstance(accountCapsule.getInstance().toBuilder() - .setBalance(oldBalance + allowance) - .setAllowance(0L) - .setLatestWithdrawTime(now) - .build()); - // todo internal tx - repository.putAccountValue(accountCapsule.createDbKey(), accountCapsule); - return allowance; - } + accountCapsule.setInstance(accountCapsule.getInstance().toBuilder() + .setBalance(oldBalance + allowance) + .setAllowance(0L) + .setLatestWithdrawTime(now) + .build()); + // todo internal tx + repository.putAccountValue(accountCapsule.createDbKey(), accountCapsule); + return allowance; + } - public void validate(Object contract, Repository repository, long now) throws ContractValidateException { - if (Objects.isNull(contract)) { - throw new ContractValidateException(CONTRACT_NULL); - } - if (repository == null) { - throw new ContractValidateException(ContractProcessorConstant.STORE_NOT_EXIST); - } - if (!(contract instanceof WithdrawRewardParam)) { - throw new ContractValidateException( - "contract type error, expected type [WithdrawRewardParam], real type[" + contract - .getClass() + "]"); - } - WithdrawRewardParam withdrawRewardParam = (WithdrawRewardParam) contract; - byte[] targetAddress = withdrawRewardParam.getTargetAddress(); - if (!DecodeUtil.addressValid(targetAddress)) { - throw new ContractValidateException("Invalid address"); - } - AccountCapsule accountCapsule = repository.getAccount(targetAddress); - DynamicPropertiesStore dynamicStore = repository.getDynamicPropertiesStore(); - ContractService contractService = ContractService.getInstance(); - String readableOwnerAddress = StringUtil.createReadableString(targetAddress); - if (accountCapsule == null) { - throw new ContractValidateException( - ACCOUNT_EXCEPTION_STR + readableOwnerAddress + "] not exists"); - } + public void validate(Object contract, Repository repository, long now) throws ContractValidateException { + if (Objects.isNull(contract)) { + throw new ContractValidateException(CONTRACT_NULL); + } + if (repository == null) { + throw new ContractValidateException(ContractProcessorConstant.STORE_NOT_EXIST); + } + if (!(contract instanceof WithdrawRewardParam)) { + throw new ContractValidateException( + "contract type error, expected type [WithdrawRewardParam], real type[" + contract + .getClass() + "]"); + } + WithdrawRewardParam withdrawRewardParam = (WithdrawRewardParam) contract; + byte[] targetAddress = withdrawRewardParam.getTargetAddress(); + if (!DecodeUtil.addressValid(targetAddress)) { + throw new ContractValidateException("Invalid address"); + } + AccountCapsule accountCapsule = repository.getAccount(targetAddress); + DynamicPropertiesStore dynamicStore = repository.getDynamicPropertiesStore(); + ContractService contractService = ContractService.getInstance(); + String readableOwnerAddress = StringUtil.createReadableString(targetAddress); + if (accountCapsule == null) { + throw new ContractValidateException( + ACCOUNT_EXCEPTION_STR + readableOwnerAddress + "] not exists"); + } - boolean isGp = CommonParameter.getInstance() - .getGenesisBlock().getWitnesses().stream().anyMatch(witness -> - Arrays.equals(targetAddress, witness.getAddress())); - if (isGp) { - throw new ContractValidateException( - ACCOUNT_EXCEPTION_STR + readableOwnerAddress - + "] is a guard representative and is not allowed to withdraw Balance"); - } + boolean isGp = CommonParameter.getInstance() + .getGenesisBlock().getWitnesses().stream().anyMatch(witness -> + Arrays.equals(targetAddress, witness.getAddress())); + if (isGp) { + throw new ContractValidateException( + ACCOUNT_EXCEPTION_STR + readableOwnerAddress + + "] is a guard representative and is not allowed to withdraw Balance"); + } - long latestWithdrawTime = accountCapsule.getLatestWithdrawTime(); - long witnessAllowanceFrozenTime = dynamicStore.getWitnessAllowanceFrozenTime() * FROZEN_PERIOD; + long latestWithdrawTime = accountCapsule.getLatestWithdrawTime(); + long witnessAllowanceFrozenTime = dynamicStore.getWitnessAllowanceFrozenTime() * FROZEN_PERIOD; - if (now - latestWithdrawTime < witnessAllowanceFrozenTime) { - throw new ContractValidateException("The last withdraw time is " - + latestWithdrawTime + ", less than 24 hours"); - } + if (now - latestWithdrawTime < witnessAllowanceFrozenTime) { + throw new ContractValidateException("The last withdraw time is " + + latestWithdrawTime + ", less than 24 hours"); + } - if (accountCapsule.getAllowance() <= 0 && - contractService.queryReward(targetAddress, repository) <= 0) { - throw new ContractValidateException("witnessAccount does not have any reward"); - } - try { - LongMath.checkedAdd(accountCapsule.getBalance(), accountCapsule.getAllowance()); - } catch (ArithmeticException e) { - logger.debug(e.getMessage(), e); - throw new ContractValidateException(e.getMessage()); - } + if (accountCapsule.getAllowance() <= 0 && + contractService.queryReward(targetAddress, repository) <= 0) { + throw new ContractValidateException("witnessAccount does not have any reward"); + } + try { + LongMath.checkedAdd(accountCapsule.getBalance(), accountCapsule.getAllowance()); + } catch (ArithmeticException e) { + logger.debug(e.getMessage(), e); + throw new ContractValidateException(e.getMessage()); } + } } diff --git a/actuator/src/main/java/org/tron/core/vm/program/Program.java b/actuator/src/main/java/org/tron/core/vm/program/Program.java index b60cfc52dc8..bd2f5b93833 100644 --- a/actuator/src/main/java/org/tron/core/vm/program/Program.java +++ b/actuator/src/main/java/org/tron/core/vm/program/Program.java @@ -1792,14 +1792,14 @@ public void withdrawReward() { WithdrawRewardParam withdrawRewardParam = new WithdrawRewardParam(); byte[] ownerAddress = TransactionTrace.convertToTronAddress(getContractAddress().getLast20Bytes()); withdrawRewardParam.setTargetAddress(ownerAddress); - try{ + try { withdrawRewardContractProcessor.validate(withdrawRewardParam, repository, getTimestamp().longValue() * 1000); long allowance = withdrawRewardContractProcessor.execute(withdrawRewardParam, repository, getTimestamp().longValue() * 1000); stackPush(new DataWord(allowance)); repository.commit(); - }catch (ContractValidateException e){ + } catch (ContractValidateException e) { logger.error("validateForWithdrawReward failure:{}", e.getMessage()); stackPushZero(); } @@ -1812,14 +1812,17 @@ public void tokenIssue(DataWord name, DataWord abbr, DataWord totalSupply, DataW TokenIssueParam tokenIssueParam = new TokenIssueParam(); tokenIssueParam.setName(name.getNoEndZeroesData()); tokenIssueParam.setAbbr(abbr.getNoEndZeroesData()); - tokenIssueParam.setTotalSupply(totalSupply.sValue().longValueExact()); - tokenIssueParam.setPrecision(precision.sValue().intValueExact()); tokenIssueParam.setOwnerAddress(ownerAddress); try { + tokenIssueParam.setTotalSupply(totalSupply.sValue().longValueExact()); + tokenIssueParam.setPrecision(precision.sValue().intValueExact()); tokenIssueProcessor.validate(tokenIssueParam, repository); tokenIssueProcessor.execute(tokenIssueParam, repository); stackPush(new DataWord(repository.getTokenIdNum())); repository.commit(); + } catch (ArithmeticException e) { + logger.error("totalSupply or precision out of long range"); + stackPushZero(); } catch (ContractValidateException e) { logger.error("validateForAssetIssue failure:{}", e.getMessage()); stackPushZero(); diff --git a/framework/src/test/java/org/tron/common/runtime/vm/Trc10Test.java b/framework/src/test/java/org/tron/common/runtime/vm/Trc10Test.java index ec131e2a7a1..3beda866ffd 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/Trc10Test.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/Trc10Test.java @@ -30,9 +30,9 @@ function TokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { return assetissue(name, abbr, totalSupply, precision); } - function UpdateAsset(trcToken tokenId, string memory desc, string - memory url) public { - updateasset(tokenId, bytes(desc), bytes(url)); + function UpdateAsset(trcToken tokenId, string memory url, string + memory desc) public { + updateasset(tokenId, bytes(url), bytes(desc)); } }*/ @Test @@ -242,9 +242,9 @@ function TokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precis assetissue(name, abbr, totalSupply, precision); assetissue(name, abbr, totalSupply, precision); } - function UpdateAsset(trcToken tokenId, string memory desc, string memory url) public { - updateasset(tokenId, bytes(desc), bytes(url)); - updateasset(tokenId, bytes(desc), bytes(url)); + function UpdateAsset(trcToken tokenId, string memory url, string memory desc) public { + updateasset(tokenId, bytes(url), bytes(desc)); + updateasset(tokenId, bytes(url), bytes(desc)); } }*/ @@ -366,11 +366,11 @@ function TokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precis assetissue(name, abbr, totalSupply, precision); newaddress.transfer(100000000); } - function UpdateAsset(trcToken tokenId, string memory desc, string memory url, address + function UpdateAsset(trcToken tokenId, string memory url, string memory desc, address addr) public { address payable newaddress = address(uint160(addr)); newaddress.transfer(100000000); - updateasset(tokenId, bytes(desc), bytes(url)); + updateasset(tokenId, bytes(url), bytes(desc)); newaddress.transfer(100000000); } }*/ @@ -495,8 +495,8 @@ function TokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precis public returns (uint) { return a.TokenIssueA(name, abbr, totalSupply, precision); } - function UpdateAsset(trcToken tokenId, string memory desc, string memory url) public { - a.UpdateAssetA(tokenId, desc, url); + function UpdateAsset(trcToken tokenId, string memory url, string memory desc) public { + a.UpdateAssetA(tokenId, url, desc); } function getContractAddress() public returns (address) { return address(a); From 54e45d09a6c60e4b637e74e15f75776c7b9c8f10 Mon Sep 17 00:00:00 2001 From: running-tomato <31307926+guoquanwu@users.noreply.github.com> Date: Tue, 1 Sep 2020 14:36:59 +0800 Subject: [PATCH 20/60] update http&rpc filter (#3376) update http&rpc filter for shielded transaction --- .../filter/LiteFnQueryGrpcInterceptor.java | 16 +++++++++++++ .../filter/LiteFnQueryHttpFilter.java | 24 +++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/framework/src/main/java/org/tron/core/services/filter/LiteFnQueryGrpcInterceptor.java b/framework/src/main/java/org/tron/core/services/filter/LiteFnQueryGrpcInterceptor.java index 42fea17cc65..cd5645f32c2 100644 --- a/framework/src/main/java/org/tron/core/services/filter/LiteFnQueryGrpcInterceptor.java +++ b/framework/src/main/java/org/tron/core/services/filter/LiteFnQueryGrpcInterceptor.java @@ -39,6 +39,14 @@ public static Set getFilterMethods() { filterMethods.add("protocol.Wallet/ScanNoteByIvk"); filterMethods.add("protocol.Wallet/ScanNoteByOvk"); filterMethods.add("protocol.Wallet/TotalTransaction"); + filterMethods.add("protocol.Wallet/GetMarketOrderByAccount"); + filterMethods.add("protocol.Wallet/GetMarketOrderById"); + filterMethods.add("protocol.Wallet/GetMarketPriceByPair"); + filterMethods.add("protocol.Wallet/GetMarketOrderListByPair"); + filterMethods.add("protocol.Wallet/GetMarketPairList"); + filterMethods.add("protocol.Wallet/ScanShieldedTRC20NotesByIvk"); + filterMethods.add("protocol.Wallet/ScanShieldedTRC20NotesByOvk"); + filterMethods.add("protocol.Wallet/IsShieldedTRC20ContractNoteSpent"); // walletSolidity filterMethods.add("protocol.WalletSolidity/GetBlockByNum"); @@ -51,6 +59,14 @@ public static Set getFilterMethods() { filterMethods.add("protocol.WalletSolidity/ScanAndMarkNoteByIvk"); filterMethods.add("protocol.WalletSolidity/ScanNoteByIvk"); filterMethods.add("protocol.WalletSolidity/ScanNoteByOvk"); + filterMethods.add("protocol.WalletSolidity/GetMarketOrderByAccount"); + filterMethods.add("protocol.WalletSolidity/GetMarketOrderById"); + filterMethods.add("protocol.WalletSolidity/GetMarketPriceByPair"); + filterMethods.add("protocol.WalletSolidity/GetMarketOrderListByPair"); + filterMethods.add("protocol.WalletSolidity/GetMarketPairList"); + filterMethods.add("protocol.WalletSolidity/ScanShieldedTRC20NotesByIvk"); + filterMethods.add("protocol.WalletSolidity/ScanShieldedTRC20NotesByOvk"); + filterMethods.add("protocol.WalletSolidity/IsShieldedTRC20ContractNoteSpent"); // database filterMethods.add("protocol.Database/GetBlockByNum"); diff --git a/framework/src/main/java/org/tron/core/services/filter/LiteFnQueryHttpFilter.java b/framework/src/main/java/org/tron/core/services/filter/LiteFnQueryHttpFilter.java index a947a889b61..e80ce4ec549 100644 --- a/framework/src/main/java/org/tron/core/services/filter/LiteFnQueryHttpFilter.java +++ b/framework/src/main/java/org/tron/core/services/filter/LiteFnQueryHttpFilter.java @@ -42,6 +42,14 @@ public static Set getFilterPaths() { filterPaths.add("/wallet/scannotebyovk"); filterPaths.add("/wallet/totaltransaction"); filterPaths.add("/wallet/gettransactioninfobyblocknum"); + filterPaths.add("/wallet/getmarketorderbyaccount"); + filterPaths.add("/wallet/getmarketorderbyid"); + filterPaths.add("/wallet/getmarketpricebypair"); + filterPaths.add("/wallet/getmarketorderlistbypair"); + filterPaths.add("/wallet/getmarketpairlist"); + filterPaths.add("/wallet/scanshieldedtrc20notesbyivk"); + filterPaths.add("/wallet/scanshieldedtrc20notesbyovk"); + filterPaths.add("/wallet/isshieldedtrc20contractnotespent"); // base path: /walletsolidity filterPaths.add("/walletsolidity/getblockbyid"); @@ -57,6 +65,14 @@ public static Set getFilterPaths() { filterPaths.add("/walletsolidity/scannotebyivk"); filterPaths.add("/walletsolidity/scannotebyovk"); filterPaths.add("/walletsolidity/gettransactioninfobyblocknum"); + filterPaths.add("/walletsolidity/getmarketorderbyaccount"); + filterPaths.add("/walletsolidity/getmarketorderbyid"); + filterPaths.add("/walletsolidity/getmarketpricebypair"); + filterPaths.add("/walletsolidity/getmarketorderlistbypair"); + filterPaths.add("/walletsolidity/getmarketpairlist"); + filterPaths.add("/walletsolidity/scanshieldedtrc20notesbyivk"); + filterPaths.add("/walletsolidity/scanshieldedtrc20notesbyovk"); + filterPaths.add("/walletsolidity/isshieldedtrc20contractnotespent"); // base path: /walletpbft filterPaths.add("/walletpbft/getblockbyid"); @@ -71,6 +87,14 @@ public static Set getFilterPaths() { filterPaths.add("/walletpbft/scanandmarknotebyivk"); filterPaths.add("/walletpbft/scannotebyivk"); filterPaths.add("/walletpbft/scannotebyovk"); + filterPaths.add("/walletpbft/getmarketorderbyaccount"); + filterPaths.add("/walletpbft/getmarketorderbyid"); + filterPaths.add("/walletpbft/getmarketpricebypair"); + filterPaths.add("/walletpbft/getmarketorderlistbypair"); + filterPaths.add("/walletpbft/getmarketpairlist"); + filterPaths.add("/walletpbft/scanshieldedtrc20notesbyivk"); + filterPaths.add("/walletpbft/scanshieldedtrc20notesbyovk"); + filterPaths.add("/walletpbft/isshieldedtrc20contractnotespent"); } @Override From 3c438f4473f46946d95f774fe850c2d57640a7f2 Mon Sep 17 00:00:00 2001 From: lvs007 Date: Tue, 8 Sep 2020 16:06:15 +0800 Subject: [PATCH 21/60] support one node start more sr --- .../org/tron/common/utils/ForkController.java | 2 +- .../java/org/tron/core/config/Parameter.java | 10 +++---- .../org/tron/consensus/pbft/PbftManager.java | 9 ++++-- .../consensus/pbft/PbftMessageHandle.java | 28 +++++++++++++++---- .../consensus/pbft/message/PbftMessage.java | 23 +++++++-------- .../java/org/tron/core/net/PbftHandler.java | 16 ++++++++++- 6 files changed, 61 insertions(+), 27 deletions(-) diff --git a/chainbase/src/main/java/org/tron/common/utils/ForkController.java b/chainbase/src/main/java/org/tron/common/utils/ForkController.java index b137dab7bb9..fa21aeceefa 100644 --- a/chainbase/src/main/java/org/tron/common/utils/ForkController.java +++ b/chainbase/src/main/java/org/tron/common/utils/ForkController.java @@ -83,7 +83,7 @@ private boolean passNew(int version) { ++count; } } - return count >= versionEnum.getHardForkCount(); + return count >= versionEnum.getHardForkRate() * manager.getWitnesses().size() / 10 + 1; } diff --git a/common/src/main/java/org/tron/core/config/Parameter.java b/common/src/main/java/org/tron/core/config/Parameter.java index b3f9d5e25a7..cee7c313164 100644 --- a/common/src/main/java/org/tron/core/config/Parameter.java +++ b/common/src/main/java/org/tron/core/config/Parameter.java @@ -12,20 +12,20 @@ public enum ForkBlockVersionEnum { VERSION_3_6_5(9, 0L, 0), VERSION_3_6_6(10, 0L, 0), VERSION_4_0(16, 0L, 0), - VERSION_4_0_1(17, 1596780000000L, 22),//GMT 2020-08-07 06:00:00 - VERSION_4_1(19, 1596780000000L, 22);//GMT 2020-08-07 06:00:00 + VERSION_4_0_1(17, 1596780000000L, 0.8),//GMT 2020-08-07 06:00:00,0.8 means 22 SR upgrade + VERSION_4_1(19, 1596780000000L, 0.8);//GMT 2020-08-07 06:00:00,0.8 means 22 SR upgrade @Getter private int value; @Getter private long hardForkTime; @Getter - private int hardForkCount; + private double hardForkRate; - ForkBlockVersionEnum(int value, long hardForkTime, int hardForkCount) { + ForkBlockVersionEnum(int value, long hardForkTime, double hardForkRate) { this.value = value; this.hardForkTime = hardForkTime; - this.hardForkCount = hardForkCount; + this.hardForkRate = hardForkRate; } public static ForkBlockVersionEnum getForkBlockVersionEnum(int value) { diff --git a/consensus/src/main/java/org/tron/consensus/pbft/PbftManager.java b/consensus/src/main/java/org/tron/consensus/pbft/PbftManager.java index f3de0c5c6d9..9b2a902dc92 100644 --- a/consensus/src/main/java/org/tron/consensus/pbft/PbftManager.java +++ b/consensus/src/main/java/org/tron/consensus/pbft/PbftManager.java @@ -9,6 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.tron.consensus.base.Param; +import org.tron.consensus.base.Param.Miner; import org.tron.consensus.dpos.MaintenanceManager; import org.tron.consensus.pbft.message.PbftBaseMessage; import org.tron.consensus.pbft.message.PbftMessage; @@ -43,7 +44,9 @@ public void blockPrePrepare(BlockCapsule block, long epoch) { } if (!pbftMessageHandle.isSyncing()) { if (Param.getInstance().isEnable()) { - doAction(PbftMessage.prePrepareBlockMsg(block, epoch)); + for (Miner miner : Param.getInstance().getMiners()) { + doAction(PbftMessage.prePrepareBlockMsg(block, epoch, miner)); + } } else { doAction(PbftMessage.fullNodePrePrepareBlockMsg(block, epoch)); } @@ -56,7 +59,9 @@ public void srPrePrepare(BlockCapsule block, List currentWitness, lo } if (!pbftMessageHandle.isSyncing()) { if (Param.getInstance().isEnable()) { - doAction(PbftMessage.prePrepareSRLMsg(block, currentWitness, epoch)); + for (Miner miner : Param.getInstance().getMiners()) { + doAction(PbftMessage.prePrepareSRLMsg(block, currentWitness, epoch, miner)); + } } else { doAction(PbftMessage.fullNodePrePrepareSRLMsg(block, currentWitness, epoch)); } diff --git a/consensus/src/main/java/org/tron/consensus/pbft/PbftMessageHandle.java b/consensus/src/main/java/org/tron/consensus/pbft/PbftMessageHandle.java index 503a916b76c..182f97b3275 100644 --- a/consensus/src/main/java/org/tron/consensus/pbft/PbftMessageHandle.java +++ b/consensus/src/main/java/org/tron/consensus/pbft/PbftMessageHandle.java @@ -8,6 +8,7 @@ import com.google.common.collect.Sets; import com.google.common.util.concurrent.AtomicLongMap; import com.google.protobuf.ByteString; +import java.security.SignatureException; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -23,6 +24,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.tron.consensus.base.Param; +import org.tron.consensus.base.Param.Miner; import org.tron.consensus.dpos.MaintenanceManager; import org.tron.consensus.pbft.message.PbftBaseMessage; import org.tron.consensus.pbft.message.PbftMessage; @@ -94,8 +96,16 @@ public void onPrePrepare(PbftMessage message) { if (!checkIsCanSendMsg(message)) { return; } - PbftBaseMessage paMessage = message.buildPrePareMessage(); - forwardMessage(paMessage); + for (Miner miner : Param.getInstance().getMiners()) { + PbftMessage paMessage = message.buildPrePareMessage(miner); + forwardMessage(paMessage); + try { + paMessage.analyzeSignature(); + } catch (SignatureException e) { + logger.error("", e); + } + onPrepare(paMessage); + } if (message.getDataType() == DataType.SRL) { srPbftMessage = message; } @@ -130,9 +140,17 @@ public synchronized void onPrepare(PbftMessage message) { if (agCou >= Param.getInstance().getAgreeNodeCount()) { agreePare.remove(message.getDataKey()); //Entering the submission stage - PbftMessage cmMessage = message.buildCommitMessage(); - doneMsg.put(message.getNo(), cmMessage); - forwardMessage(cmMessage); + for (Miner miner : Param.getInstance().getMiners()) { + PbftMessage cmMessage = message.buildCommitMessage(miner); + doneMsg.put(message.getNo(), cmMessage); + forwardMessage(cmMessage); + try { + cmMessage.analyzeSignature(); + } catch (SignatureException e) { + logger.error("", e); + } + onCommit(cmMessage); + } } } //Subsequent votes will definitely not be satisfied, timeout will be automatically cleared. diff --git a/consensus/src/main/java/org/tron/consensus/pbft/message/PbftMessage.java b/consensus/src/main/java/org/tron/consensus/pbft/message/PbftMessage.java index 513368ebc2c..d157c1f8335 100644 --- a/consensus/src/main/java/org/tron/consensus/pbft/message/PbftMessage.java +++ b/consensus/src/main/java/org/tron/consensus/pbft/message/PbftMessage.java @@ -5,7 +5,6 @@ import org.tron.common.crypto.ECKey; import org.tron.common.crypto.ECKey.ECDSASignature; import org.tron.common.utils.Sha256Hash; -import org.tron.consensus.base.Param; import org.tron.consensus.base.Param.Miner; import org.tron.core.capsule.BlockCapsule; import org.tron.core.net.message.MessageTypes; @@ -28,9 +27,9 @@ public String getNo() { return pbftMessage.getRawData().getViewN() + "_" + pbftMessage.getRawData().getDataType(); } - public static PbftMessage prePrepareBlockMsg(BlockCapsule block, long epoch) { + public static PbftMessage prePrepareBlockMsg(BlockCapsule block, long epoch, Miner miner) { return buildCommon(DataType.BLOCK, block.getBlockId().getByteString(), block, epoch, - block.getNum()); + block.getNum(), miner); } public static PbftMessage fullNodePrePrepareBlockMsg(BlockCapsule block, @@ -40,10 +39,10 @@ public static PbftMessage fullNodePrePrepareBlockMsg(BlockCapsule block, } public static PbftMessage prePrepareSRLMsg(BlockCapsule block, - List currentWitness, long epoch) { + List currentWitness, long epoch, Miner miner) { SRL.Builder srListBuilder = SRL.newBuilder(); ByteString data = srListBuilder.addAllSrAddress(currentWitness).build().toByteString(); - return buildCommon(DataType.SRL, data, block, epoch, epoch); + return buildCommon(DataType.SRL, data, block, epoch, epoch, miner); } public static PbftMessage fullNodePrePrepareSRLMsg(BlockCapsule block, @@ -54,9 +53,8 @@ public static PbftMessage fullNodePrePrepareSRLMsg(BlockCapsule block, } private static PbftMessage buildCommon(DataType dataType, ByteString data, BlockCapsule block, - long epoch, long viewN) { + long epoch, long viewN, Miner miner) { PbftMessage pbftMessage = new PbftMessage(); - Miner miner = Param.getInstance().getMiner(); ECKey ecKey = ECKey.fromPrivate(miner.getPrivateKey()); Raw.Builder rawBuilder = Raw.newBuilder(); PBFTMessage.Builder builder = PBFTMessage.newBuilder(); @@ -87,17 +85,16 @@ private static PbftMessage buildFullNodeCommon(DataType dataType, ByteString dat return pbftMessage; } - public PbftMessage buildPrePareMessage() { - return buildMessageCapsule(MsgType.PREPARE); + public PbftMessage buildPrePareMessage(Miner miner) { + return buildMessageCapsule(MsgType.PREPARE, miner); } - public PbftMessage buildCommitMessage() { - return buildMessageCapsule(MsgType.COMMIT); + public PbftMessage buildCommitMessage(Miner miner) { + return buildMessageCapsule(MsgType.COMMIT, miner); } - private PbftMessage buildMessageCapsule(MsgType type) { + private PbftMessage buildMessageCapsule(MsgType type, Miner miner) { PbftMessage pbftMessage = new PbftMessage(); - Miner miner = Param.getInstance().getMiners().get(0); ECKey ecKey = ECKey.fromPrivate(miner.getPrivateKey()); PBFTMessage.Builder builder = PBFTMessage.newBuilder(); Raw.Builder rawBuilder = Raw.newBuilder(); diff --git a/framework/src/main/java/org/tron/core/net/PbftHandler.java b/framework/src/main/java/org/tron/core/net/PbftHandler.java index df10e5b8c7f..4120edce707 100644 --- a/framework/src/main/java/org/tron/core/net/PbftHandler.java +++ b/framework/src/main/java/org/tron/core/net/PbftHandler.java @@ -12,6 +12,7 @@ import org.springframework.stereotype.Component; import org.tron.common.overlay.server.Channel; import org.tron.common.overlay.server.MessageQueue; +import org.tron.common.overlay.server.SyncPool; import org.tron.consensus.base.Param; import org.tron.consensus.pbft.PbftManager; import org.tron.consensus.pbft.message.PbftBaseMessage; @@ -35,6 +36,9 @@ public class PbftHandler extends SimpleChannelInboundHandler { @Autowired private PbftManager pbftManager; + @Autowired + private SyncPool syncPool; + @Override public void channelRead0(final ChannelHandlerContext ctx, PbftMessage msg) throws Exception { msgQueue.receivedMessage(msg); @@ -53,7 +57,7 @@ public void channelRead0(final ChannelHandlerContext ctx, PbftMessage msg) throw throw new P2pException(P2pException.TypeEnum.BAD_MESSAGE, msg.toString()); } msgCache.put(key, true); - pbftManager.forwardMessage(msg); + forwardMessage(msg); pbftManager.doAction(msg); } finally { lock.unlock(); @@ -61,6 +65,16 @@ public void channelRead0(final ChannelHandlerContext ctx, PbftMessage msg) throw } + public void forwardMessage(PbftBaseMessage message) { + if (syncPool == null) { + return; + } + syncPool.getActivePeers().stream().filter(peerConnection -> !peerConnection.equals(peer)) + .forEach(peerConnection -> { + peerConnection.sendMessage(message); + }); + } + @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { peer.processException(cause); From cb388a8bf161cdbfecc312cef49997093f5b80f6 Mon Sep 17 00:00:00 2001 From: lvs007 Date: Tue, 8 Sep 2020 16:17:54 +0800 Subject: [PATCH 22/60] remove the div 10 --- .../src/main/java/org/tron/common/utils/ForkController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chainbase/src/main/java/org/tron/common/utils/ForkController.java b/chainbase/src/main/java/org/tron/common/utils/ForkController.java index fa21aeceefa..86a4f8206c8 100644 --- a/chainbase/src/main/java/org/tron/common/utils/ForkController.java +++ b/chainbase/src/main/java/org/tron/common/utils/ForkController.java @@ -83,7 +83,7 @@ private boolean passNew(int version) { ++count; } } - return count >= versionEnum.getHardForkRate() * manager.getWitnesses().size() / 10 + 1; + return count >= versionEnum.getHardForkRate() * manager.getWitnesses().size() + 1; } From 1860033c457656fce51ccbc83921bd7d46019f6b Mon Sep 17 00:00:00 2001 From: lvs007 Date: Tue, 8 Sep 2020 16:53:05 +0800 Subject: [PATCH 23/60] filter the not sr miner --- .../java/org/tron/common/utils/ForkController.java | 3 ++- .../main/java/org/tron/core/config/Parameter.java | 8 ++++---- .../java/org/tron/consensus/pbft/PbftManager.java | 2 +- .../org/tron/consensus/pbft/PbftMessageHandle.java | 14 ++++++++++++-- 4 files changed, 19 insertions(+), 8 deletions(-) diff --git a/chainbase/src/main/java/org/tron/common/utils/ForkController.java b/chainbase/src/main/java/org/tron/common/utils/ForkController.java index 86a4f8206c8..1b26402100c 100644 --- a/chainbase/src/main/java/org/tron/common/utils/ForkController.java +++ b/chainbase/src/main/java/org/tron/common/utils/ForkController.java @@ -83,7 +83,8 @@ private boolean passNew(int version) { ++count; } } - return count >= versionEnum.getHardForkRate() * manager.getWitnesses().size() + 1; + return count >= Math + .ceil((double) versionEnum.getHardForkRate() * manager.getWitnesses().size() / 100); } diff --git a/common/src/main/java/org/tron/core/config/Parameter.java b/common/src/main/java/org/tron/core/config/Parameter.java index cee7c313164..d38c6a5a8e4 100644 --- a/common/src/main/java/org/tron/core/config/Parameter.java +++ b/common/src/main/java/org/tron/core/config/Parameter.java @@ -12,17 +12,17 @@ public enum ForkBlockVersionEnum { VERSION_3_6_5(9, 0L, 0), VERSION_3_6_6(10, 0L, 0), VERSION_4_0(16, 0L, 0), - VERSION_4_0_1(17, 1596780000000L, 0.8),//GMT 2020-08-07 06:00:00,0.8 means 22 SR upgrade - VERSION_4_1(19, 1596780000000L, 0.8);//GMT 2020-08-07 06:00:00,0.8 means 22 SR upgrade + VERSION_4_0_1(17, 1596780000000L, 80),//GMT 2020-08-07 06:00:00,80 means 22 SR upgrade + VERSION_4_1(19, 1596780000000L, 80);//GMT 2020-08-07 06:00:00,80 means 22 SR upgrade @Getter private int value; @Getter private long hardForkTime; @Getter - private double hardForkRate; + private int hardForkRate; - ForkBlockVersionEnum(int value, long hardForkTime, double hardForkRate) { + ForkBlockVersionEnum(int value, long hardForkTime, int hardForkRate) { this.value = value; this.hardForkTime = hardForkTime; this.hardForkRate = hardForkRate; diff --git a/consensus/src/main/java/org/tron/consensus/pbft/PbftManager.java b/consensus/src/main/java/org/tron/consensus/pbft/PbftManager.java index 9b2a902dc92..a7a309accfc 100644 --- a/consensus/src/main/java/org/tron/consensus/pbft/PbftManager.java +++ b/consensus/src/main/java/org/tron/consensus/pbft/PbftManager.java @@ -44,7 +44,7 @@ public void blockPrePrepare(BlockCapsule block, long epoch) { } if (!pbftMessageHandle.isSyncing()) { if (Param.getInstance().isEnable()) { - for (Miner miner : Param.getInstance().getMiners()) { + for (Miner miner : pbftMessageHandle.getSrMinerList()) { doAction(PbftMessage.prePrepareBlockMsg(block, epoch, miner)); } } else { diff --git a/consensus/src/main/java/org/tron/consensus/pbft/PbftMessageHandle.java b/consensus/src/main/java/org/tron/consensus/pbft/PbftMessageHandle.java index 182f97b3275..55598a9dae4 100644 --- a/consensus/src/main/java/org/tron/consensus/pbft/PbftMessageHandle.java +++ b/consensus/src/main/java/org/tron/consensus/pbft/PbftMessageHandle.java @@ -17,6 +17,7 @@ import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; import javax.annotation.PostConstruct; import lombok.Setter; import lombok.extern.slf4j.Slf4j; @@ -28,6 +29,7 @@ import org.tron.consensus.dpos.MaintenanceManager; import org.tron.consensus.pbft.message.PbftBaseMessage; import org.tron.consensus.pbft.message.PbftMessage; +import org.tron.core.ChainBaseManager; import org.tron.protos.Protocol.PBFTMessage.DataType; @Slf4j(topic = "pbft") @@ -69,12 +71,20 @@ public List load(String s) throws Exception { private PbftMessageAction pbftMessageAction; @Setter private MaintenanceManager maintenanceManager; + @Autowired + private ChainBaseManager chainBaseManager; @PostConstruct public void init() { start(); } + public List getSrMinerList() { + return Param.getInstance().getMiners().stream() + .filter(miner -> chainBaseManager.getWitnesses().contains(miner.getWitnessAddress())) + .collect(Collectors.toList()); + } + public void onPrePrepare(PbftMessage message) { String key = message.getNo(); if (message.isSwitch()) {//if is block chain switch,remove the before proposal @@ -96,7 +106,7 @@ public void onPrePrepare(PbftMessage message) { if (!checkIsCanSendMsg(message)) { return; } - for (Miner miner : Param.getInstance().getMiners()) { + for (Miner miner : getSrMinerList()) { PbftMessage paMessage = message.buildPrePareMessage(miner); forwardMessage(paMessage); try { @@ -140,7 +150,7 @@ public synchronized void onPrepare(PbftMessage message) { if (agCou >= Param.getInstance().getAgreeNodeCount()) { agreePare.remove(message.getDataKey()); //Entering the submission stage - for (Miner miner : Param.getInstance().getMiners()) { + for (Miner miner : getSrMinerList()) { PbftMessage cmMessage = message.buildCommitMessage(miner); doneMsg.put(message.getNo(), cmMessage); forwardMessage(cmMessage); From 27b62cd218cfa766b4b29ed9254b7311ded4c01c Mon Sep 17 00:00:00 2001 From: lvs007 Date: Tue, 8 Sep 2020 17:18:11 +0800 Subject: [PATCH 24/60] fix the test case --- framework/src/test/java/org/tron/core/pbft/PbftTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/framework/src/test/java/org/tron/core/pbft/PbftTest.java b/framework/src/test/java/org/tron/core/pbft/PbftTest.java index 076fb6f1ba5..a5d74ad7a37 100644 --- a/framework/src/test/java/org/tron/core/pbft/PbftTest.java +++ b/framework/src/test/java/org/tron/core/pbft/PbftTest.java @@ -28,7 +28,7 @@ public void testPbftSrMessage() { srList.add( ByteString.copyFrom(ByteArray.fromHexString("41df309fef25b311e7895562bd9e11aab2a58816d2"))); PbftMessage pbftSrMessage = PbftMessage - .prePrepareSRLMsg(blockCapsule, srList, 1); + .prePrepareSRLMsg(blockCapsule, srList, 1, miner); System.out.println(pbftSrMessage); } From 9aa0436799c9178dc897817071f3138f4b0278c8 Mon Sep 17 00:00:00 2001 From: lvs007 Date: Wed, 9 Sep 2020 17:04:45 +0800 Subject: [PATCH 25/60] replease miner method --- .../src/main/java/org/tron/consensus/pbft/PbftManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/consensus/src/main/java/org/tron/consensus/pbft/PbftManager.java b/consensus/src/main/java/org/tron/consensus/pbft/PbftManager.java index a7a309accfc..8d12ecbd3f4 100644 --- a/consensus/src/main/java/org/tron/consensus/pbft/PbftManager.java +++ b/consensus/src/main/java/org/tron/consensus/pbft/PbftManager.java @@ -59,7 +59,7 @@ public void srPrePrepare(BlockCapsule block, List currentWitness, lo } if (!pbftMessageHandle.isSyncing()) { if (Param.getInstance().isEnable()) { - for (Miner miner : Param.getInstance().getMiners()) { + for (Miner miner : pbftMessageHandle.getSrMinerList()) { doAction(PbftMessage.prePrepareSRLMsg(block, currentWitness, epoch, miner)); } } else { From b48390341c23e588922ab459fe80c00cc618c080 Mon Sep 17 00:00:00 2001 From: Matt Date: Thu, 10 Sep 2020 15:22:29 +0800 Subject: [PATCH 26/60] hardfork support all in one --- .../main/java/org/tron/common/utils/ForkController.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/chainbase/src/main/java/org/tron/common/utils/ForkController.java b/chainbase/src/main/java/org/tron/common/utils/ForkController.java index 1b26402100c..694734562ca 100644 --- a/chainbase/src/main/java/org/tron/common/utils/ForkController.java +++ b/chainbase/src/main/java/org/tron/common/utils/ForkController.java @@ -155,15 +155,15 @@ public synchronized void update(BlockCapsule blockCapsule) { downgrade(version, slot); byte[] stats = manager.getDynamicPropertiesStore().statsByVersion(version); + if (Objects.isNull(stats) || stats.length != witnesses.size()) { + stats = new byte[witnesses.size()]; + } + if (check(stats)) { upgrade(version, stats.length); return; } - if (Objects.isNull(stats) || stats.length != witnesses.size()) { - stats = new byte[witnesses.size()]; - } - stats[slot] = VERSION_UPGRADE; manager.getDynamicPropertiesStore().statsByVersion(version, stats); logger.info( From 8d537ad044cbb63cf9b3a147ed21c808eca9987e Mon Sep 17 00:00:00 2001 From: xiangdepeng Date: Thu, 10 Sep 2020 15:40:17 +0800 Subject: [PATCH 27/60] add needCheckFrozeTime for unstake and withdrawReward --- .../org/tron/core/vm/nativecontract/UnstakeProcessor.java | 5 ++++- .../tron/core/vm/nativecontract/WithdrawRewardProcessor.java | 4 +++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/UnstakeProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/UnstakeProcessor.java index ccf9cd0e43b..ead2a9ee875 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/UnstakeProcessor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/UnstakeProcessor.java @@ -2,6 +2,7 @@ import com.google.protobuf.ByteString; import lombok.extern.slf4j.Slf4j; +import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.DecodeUtil; import org.tron.common.utils.StringUtil; import org.tron.core.actuator.ActuatorConstant; @@ -75,7 +76,9 @@ public void validate(UnstakeParam unstakeParam, Repository repository) throw new ContractValidateException("no frozenBalance(BANDWIDTH)"); } - if (accountCapsule.getFrozenList().get(0).getExpireTime() > now) { + boolean needCheckFrozeTime = CommonParameter.getInstance() + .getCheckFrozenTime() == 1;//for test + if (needCheckFrozeTime && accountCapsule.getFrozenList().get(0).getExpireTime() > now) { throw new ContractValidateException("It's not time to unfreeze(BANDWIDTH)."); } } diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawRewardProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawRewardProcessor.java index c99ed6412e9..f828677348b 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawRewardProcessor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawRewardProcessor.java @@ -83,7 +83,9 @@ public void validate(Object contract, Repository repository, long now) throws Co long latestWithdrawTime = accountCapsule.getLatestWithdrawTime(); long witnessAllowanceFrozenTime = dynamicStore.getWitnessAllowanceFrozenTime() * FROZEN_PERIOD; - if (now - latestWithdrawTime < witnessAllowanceFrozenTime) { + boolean needCheckFrozeTime = CommonParameter.getInstance() + .getCheckFrozenTime() == 1;//for test + if (needCheckFrozeTime && (now - latestWithdrawTime < witnessAllowanceFrozenTime)) { throw new ContractValidateException("The last withdraw time is " + latestWithdrawTime + ", less than 24 hours"); } From d49c1fff869a8814f322ea7b53ad2c5e9401550b Mon Sep 17 00:00:00 2001 From: xiangdepeng Date: Thu, 10 Sep 2020 15:51:46 +0800 Subject: [PATCH 28/60] refactor name for needCheckFrozenTime --- .../org/tron/core/vm/nativecontract/UnstakeProcessor.java | 4 ++-- .../tron/core/vm/nativecontract/WithdrawRewardProcessor.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/UnstakeProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/UnstakeProcessor.java index ead2a9ee875..6d81f6be799 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/UnstakeProcessor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/UnstakeProcessor.java @@ -76,9 +76,9 @@ public void validate(UnstakeParam unstakeParam, Repository repository) throw new ContractValidateException("no frozenBalance(BANDWIDTH)"); } - boolean needCheckFrozeTime = CommonParameter.getInstance() + boolean needCheckFrozenTime = CommonParameter.getInstance() .getCheckFrozenTime() == 1;//for test - if (needCheckFrozeTime && accountCapsule.getFrozenList().get(0).getExpireTime() > now) { + if (needCheckFrozenTime && accountCapsule.getFrozenList().get(0).getExpireTime() > now) { throw new ContractValidateException("It's not time to unfreeze(BANDWIDTH)."); } } diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawRewardProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawRewardProcessor.java index f828677348b..9ead8a75355 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawRewardProcessor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawRewardProcessor.java @@ -83,9 +83,9 @@ public void validate(Object contract, Repository repository, long now) throws Co long latestWithdrawTime = accountCapsule.getLatestWithdrawTime(); long witnessAllowanceFrozenTime = dynamicStore.getWitnessAllowanceFrozenTime() * FROZEN_PERIOD; - boolean needCheckFrozeTime = CommonParameter.getInstance() + boolean needCheckFrozenTime = CommonParameter.getInstance() .getCheckFrozenTime() == 1;//for test - if (needCheckFrozeTime && (now - latestWithdrawTime < witnessAllowanceFrozenTime)) { + if (needCheckFrozenTime && (now - latestWithdrawTime < witnessAllowanceFrozenTime)) { throw new ContractValidateException("The last withdraw time is " + latestWithdrawTime + ", less than 24 hours"); } From 5e94706a38544a3a46302de6d42015b96fed8961 Mon Sep 17 00:00:00 2001 From: "ray.wu" Date: Mon, 14 Sep 2020 19:24:25 +0800 Subject: [PATCH 29/60] Bugfix: fix event filter --- .../java/org/tron/common/logsfilter/EventPluginLoader.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/framework/src/main/java/org/tron/common/logsfilter/EventPluginLoader.java b/framework/src/main/java/org/tron/common/logsfilter/EventPluginLoader.java index 0f8e636f0f7..857f3d7419c 100644 --- a/framework/src/main/java/org/tron/common/logsfilter/EventPluginLoader.java +++ b/framework/src/main/java/org/tron/common/logsfilter/EventPluginLoader.java @@ -13,6 +13,7 @@ import org.pf4j.DefaultPluginManager; import org.pf4j.ManifestPluginDescriptorFinder; import org.pf4j.PluginManager; +import org.spongycastle.util.encoders.Hex; import org.springframework.util.StringUtils; import org.tron.common.logsfilter.nativequeue.NativeMessageQueue; import org.tron.common.logsfilter.trigger.BlockLogTrigger; @@ -111,7 +112,6 @@ public static boolean matchFilter(ContractTrigger trigger) { if (!matched) { return false; } - return filterContractAddress(trigger, filterQuery.getContractAddressList()) && filterContractTopicList(trigger, filterQuery.getContractTopicList()); } @@ -147,8 +147,10 @@ private static boolean filterContractTopicList(ContractTrigger trigger, List hset = null; if (trigger instanceof ContractLogTrigger) { hset = ((ContractLogTrigger) trigger).getTopicList().stream().collect(Collectors.toSet()); - } else { + } else if (trigger instanceof ContractEventTrigger) { hset = new HashSet<>(((ContractEventTrigger) trigger).getTopicMap().values()); + } else if (trigger instanceof ContractTrigger) { + hset = trigger.getLogInfo().getClonedTopics().stream().map(Hex::toHexString).collect(Collectors.toSet()); } for (String top : topList) { From 25599e92e0b375d95e26ebe899e6803b224aebdd Mon Sep 17 00:00:00 2001 From: "ray.wu" Date: Tue, 15 Sep 2020 11:26:35 +0800 Subject: [PATCH 30/60] fix sonar check --- .../java/org/tron/common/logsfilter/EventPluginLoader.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/framework/src/main/java/org/tron/common/logsfilter/EventPluginLoader.java b/framework/src/main/java/org/tron/common/logsfilter/EventPluginLoader.java index 857f3d7419c..ef218dc84af 100644 --- a/framework/src/main/java/org/tron/common/logsfilter/EventPluginLoader.java +++ b/framework/src/main/java/org/tron/common/logsfilter/EventPluginLoader.java @@ -150,7 +150,8 @@ private static boolean filterContractTopicList(ContractTrigger trigger, List(((ContractEventTrigger) trigger).getTopicMap().values()); } else if (trigger instanceof ContractTrigger) { - hset = trigger.getLogInfo().getClonedTopics().stream().map(Hex::toHexString).collect(Collectors.toSet()); + hset = trigger.getLogInfo().getClonedTopics() + .stream().map(Hex::toHexString).collect(Collectors.toSet()); } for (String top : topList) { From ce52721b78c463d284dd9a4b82d0ff8cc477044e Mon Sep 17 00:00:00 2001 From: sean-liu55 Date: Thu, 24 Sep 2020 16:52:41 +0800 Subject: [PATCH 31/60] rm useless parameter --- protocol/src/main/protos/core/contract/market_contract.proto | 1 - 1 file changed, 1 deletion(-) diff --git a/protocol/src/main/protos/core/contract/market_contract.proto b/protocol/src/main/protos/core/contract/market_contract.proto index 79abade618c..e1274350036 100644 --- a/protocol/src/main/protos/core/contract/market_contract.proto +++ b/protocol/src/main/protos/core/contract/market_contract.proto @@ -11,7 +11,6 @@ message MarketSellAssetContract { int64 sell_token_quantity = 3; bytes buy_token_id = 4; int64 buy_token_quantity = 5; // min to receive - bytes pre_price_key = 6; // order price position } message MarketCancelOrderContract { From 3b7101121ae50deb34204586e7de5437fd6b39be Mon Sep 17 00:00:00 2001 From: sean-liu55 Date: Thu, 24 Sep 2020 17:01:39 +0800 Subject: [PATCH 32/60] rm useless test --- .../actuator/MarketSellAssetActuatorTest.java | 122 +----------------- 1 file changed, 2 insertions(+), 120 deletions(-) diff --git a/framework/src/test/java/org/tron/core/actuator/MarketSellAssetActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/MarketSellAssetActuatorTest.java index 88e27a9b066..8b3285f8714 100644 --- a/framework/src/test/java/org/tron/core/actuator/MarketSellAssetActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/MarketSellAssetActuatorTest.java @@ -205,20 +205,6 @@ private Any getContract(String address, String sellTokenId, long sellTokenQuanti .build()); } - private Any getContract(String address, String sellTokenId, long sellTokenQuantity, - String buyTokenId, long buyTokenQuantity, ByteString prePriceKey) { - - return Any.pack( - MarketSellAssetContract.newBuilder() - .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(address))) - .setSellTokenId(ByteString.copyFrom(sellTokenId.getBytes())) - .setSellTokenQuantity(sellTokenQuantity) - .setBuyTokenId(ByteString.copyFrom(buyTokenId.getBytes())) - .setBuyTokenQuantity(buyTokenQuantity) - .setPrePriceKey(prePriceKey) - .build()); - } - //test case // // validate: @@ -623,107 +609,9 @@ private void prepareAccount(String sellTokenId, String buyTokenId, Assert.assertEquals(sellTokenQuant, (long) accountCapsule.getAssetMapV2().get(sellTokenId)); } - /** - * price exist - */ - @Test - public void validateSuccessWithPositionPriceExist() throws Exception { - - InitAsset(); - - //(sell id_1 and buy id_2) - // TOKEN_ID_ONE has the same value as TOKEN_ID_ONE - String sellTokenId = TOKEN_ID_ONE; - long sellTokenQuant = 100L; - String buyTokenId = TOKEN_ID_TWO; - long buyTokenQuant = 219L; - byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); - - prepareAccount(sellTokenId, buyTokenId, sellTokenQuant, buyTokenQuant, ownerAddress); - - //MAX_SEARCH_NUM = 10 - for (int i = 0; i < 20; i++) { - byte[] prePriceKey = null; - if (i != 0) { - prePriceKey = MarketUtils - .createPairPriceKey(TOKEN_ID_ONE.getBytes(), TOKEN_ID_TWO.getBytes(), 100L, - 200L + i - 1); - } - - addOrder(TOKEN_ID_ONE, 100L, TOKEN_ID_TWO, - 200L + i, OWNER_ADDRESS_FIRST, prePriceKey); - } - - byte[] prePriceKey = MarketUtils - .createPairPriceKey(TOKEN_ID_ONE.getBytes(), TOKEN_ID_TWO.getBytes(), 100L, 200L); - - // do process - MarketSellAssetActuator actuator = new MarketSellAssetActuator(); - actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny(getContract( - OWNER_ADDRESS_FIRST, sellTokenId, sellTokenQuant, buyTokenId, buyTokenQuant, - ByteString.copyFrom(prePriceKey))); - - try { - actuator.validate(); - } catch (ContractValidateException e) { - fail("validateSuccess error"); - } - } - - /** - * validate Success with position, result is Success . - */ - @Test - public void validateSuccessWithPositionLimitCount() throws Exception { - - InitAsset(); - - //(sell id_1 and buy id_2) - // TOKEN_ID_ONE has the same value as TOKEN_ID_ONE - String sellTokenId = TOKEN_ID_ONE; - long sellTokenQuant = 100L; - String buyTokenId = TOKEN_ID_TWO; - long buyTokenQuant = 300L; - byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); - - prepareAccount(sellTokenId, buyTokenId, sellTokenQuant, buyTokenQuant, ownerAddress); - - //MAX_SEARCH_NUM = 10 - for (int i = 0; i < 20; i++) { - byte[] prePriceKey = null; - if (i != 0) { - prePriceKey = MarketUtils - .createPairPriceKey(TOKEN_ID_ONE.getBytes(), TOKEN_ID_TWO.getBytes(), 100L, - 200L + i - 1); - } - - addOrder(TOKEN_ID_ONE, 100L, TOKEN_ID_TWO, - 200L + i, OWNER_ADDRESS_FIRST, prePriceKey); - } - - byte[] prePriceKey = MarketUtils - .createPairPriceKey(TOKEN_ID_ONE.getBytes(), TOKEN_ID_TWO.getBytes(), 100L, 210L); - - // do process - MarketSellAssetActuator actuator = new MarketSellAssetActuator(); - actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny(getContract( - OWNER_ADDRESS_FIRST, sellTokenId, sellTokenQuant, buyTokenId, buyTokenQuant, - ByteString.copyFrom(prePriceKey))); - - try { - actuator.validate(); - } catch (ContractValidateException e) { - fail("validateSuccess error"); - } - } private void addOrder(String sellTokenId, long sellTokenQuant, String buyTokenId, long buyTokenQuant, String ownAddress) throws Exception { - addOrder(sellTokenId, sellTokenQuant, buyTokenId, buyTokenQuant, ownAddress, null); - } - - private void addOrder(String sellTokenId, long sellTokenQuant, - String buyTokenId, long buyTokenQuant, String ownAddress, byte[] prePreKey) throws Exception { byte[] ownerAddress = ByteArray.fromHexString(ownAddress); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); @@ -733,14 +621,8 @@ private void addOrder(String sellTokenId, long sellTokenQuant, // do process MarketSellAssetActuator actuator = new MarketSellAssetActuator(); - if (prePreKey == null || prePreKey.length == 0) { - actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny(getContract( - ownAddress, sellTokenId, sellTokenQuant, buyTokenId, buyTokenQuant)); - } else { - actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny(getContract( - ownAddress, sellTokenId, sellTokenQuant, buyTokenId, buyTokenQuant, - ByteString.copyFrom(prePreKey))); - } + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny(getContract( + ownAddress, sellTokenId, sellTokenQuant, buyTokenId, buyTokenQuant)); TransactionResultCapsule ret = new TransactionResultCapsule(); actuator.validate(); From 19ba1ecae7c7815bb5ad7be8de4805be939edd6a Mon Sep 17 00:00:00 2001 From: renchenchang Date: Wed, 14 Oct 2020 18:53:17 +0800 Subject: [PATCH 33/60] fix name parse error --- .../org/tron/core/services/http/JsonFormat.java | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/framework/src/main/java/org/tron/core/services/http/JsonFormat.java b/framework/src/main/java/org/tron/core/services/http/JsonFormat.java index 755b79e7537..0a1bad1c4b3 100644 --- a/framework/src/main/java/org/tron/core/services/http/JsonFormat.java +++ b/framework/src/main/java/org/tron/core/services/http/JsonFormat.java @@ -29,6 +29,8 @@ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.alibaba.fastjson.parser.ParserConfig; import com.google.protobuf.ByteString; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.EnumDescriptor; @@ -754,13 +756,21 @@ static String escapeBytesSelfType(ByteString input, final String fliedName) { if (HttpSelfFormatFieldName.isAddressFormat(fliedName)) { return StringUtil.encode58Check(input.toByteArray()); } - //Normal String if (HttpSelfFormatFieldName.isNameStringFormat(fliedName)) { String result = new String(input.toByteArray()); - return result.replaceAll("\"", "\\\\\""); + result = result.replaceAll("\"", "\\\\\""); + try { + DefaultJSONParser parser = new DefaultJSONParser(result, ParserConfig.getGlobalInstance(), + 0); + Object value = parser.parse(); + parser.handleResovleTask(value); + parser.close(); + return result; + } catch (Exception e) { + return ByteArray.toHexString(input.toByteArray()); + } } - //HEX return ByteArray.toHexString(input.toByteArray()); } From adae3f5d80d6c016523459cabed92fd62e76ea8c Mon Sep 17 00:00:00 2001 From: running-tomato <31307926+guoquanwu@users.noreply.github.com> Date: Thu, 15 Oct 2020 13:54:18 +0800 Subject: [PATCH 34/60] revert SR reward (#3440) --- .../actuator/WithdrawBalanceActuator.java | 5 - .../org/tron/core/db/DelegationService.java | 5 - .../org/tron/core/store/DelegationStore.java | 75 ---- .../core/store/DynamicPropertiesStore.java | 14 +- .../common/parameter/CommonParameter.java | 7 - .../src/main/java/org/tron/core/Constant.java | 1 - .../tron/core/exception/AddressNotFound.java | 12 - .../tron/core/exception/InvalidAddress.java | 12 - .../consensus/dpos/MaintenanceManager.java | 2 - .../src/main/java/org/tron/core/Wallet.java | 319 ------------------ .../java/org/tron/core/config/args/Args.java | 5 - .../services/http/FullNodeHttpApiService.java | 27 -- ...GetAccountLastUnwithdrawRewardServlet.java | 49 --- .../http/GetAccountRewardByCycleServlet.java | 55 --- .../services/http/GetCurrentCycleService.java | 30 -- ...GetNowSRAnnualizedRateOfReturnServlet.java | 83 ----- .../http/GetSRDividendsByCycleServlet.java | 57 ---- .../http/GetSRProfitByCycleServlet.java | 57 ---- .../org/tron/core/services/http/Util.java | 19 -- .../test/java/org/tron/core/WalletTest.java | 122 ------- .../core/services/DelegationServiceTest.java | 11 - .../common/client/utils/HttpMethed.java | 177 ---------- .../wallet/dailybuild/http/HttpSrReward.java | 163 --------- .../http/HttpTestQueryReward001.java | 161 --------- .../onlinestress/TestApproveProposal.java | 34 -- .../onlinestress/TestSrRewardOnlineData.java | 216 ------------ 26 files changed, 1 insertion(+), 1717 deletions(-) delete mode 100644 common/src/main/java/org/tron/core/exception/AddressNotFound.java delete mode 100644 common/src/main/java/org/tron/core/exception/InvalidAddress.java delete mode 100644 framework/src/main/java/org/tron/core/services/http/GetAccountLastUnwithdrawRewardServlet.java delete mode 100644 framework/src/main/java/org/tron/core/services/http/GetAccountRewardByCycleServlet.java delete mode 100644 framework/src/main/java/org/tron/core/services/http/GetCurrentCycleService.java delete mode 100644 framework/src/main/java/org/tron/core/services/http/GetNowSRAnnualizedRateOfReturnServlet.java delete mode 100644 framework/src/main/java/org/tron/core/services/http/GetSRDividendsByCycleServlet.java delete mode 100644 framework/src/main/java/org/tron/core/services/http/GetSRProfitByCycleServlet.java delete mode 100644 framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpSrReward.java delete mode 100644 framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestQueryReward001.java delete mode 100644 framework/src/test/java/stest/tron/wallet/onlinestress/TestSrRewardOnlineData.java diff --git a/actuator/src/main/java/org/tron/core/actuator/WithdrawBalanceActuator.java b/actuator/src/main/java/org/tron/core/actuator/WithdrawBalanceActuator.java index 5b3aa2ccc8d..4a2e7f7e18d 100755 --- a/actuator/src/main/java/org/tron/core/actuator/WithdrawBalanceActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/WithdrawBalanceActuator.java @@ -53,11 +53,6 @@ public boolean execute(Object result) throws ContractExeException { delegationService.withdrawReward(withdrawBalanceContract.getOwnerAddress() .toByteArray()); - - delegationService.getDelegationStore().setLastWithdrawCycle( - dynamicStore.getCurrentCycleNumber(), withdrawBalanceContract.getOwnerAddress() - .toByteArray()); - AccountCapsule accountCapsule = accountStore. get(withdrawBalanceContract.getOwnerAddress().toByteArray()); long oldBalance = accountCapsule.getBalance(); diff --git a/chainbase/src/main/java/org/tron/core/db/DelegationService.java b/chainbase/src/main/java/org/tron/core/db/DelegationService.java index 940c9afe8a2..a0445e247f8 100644 --- a/chainbase/src/main/java/org/tron/core/db/DelegationService.java +++ b/chainbase/src/main/java/org/tron/core/db/DelegationService.java @@ -66,8 +66,6 @@ public void payStandbyWitness() { double eachVotePay = (double) totalPay / voteSum; long pay = (long) (getWitnessByAddress(b).getVoteCount() * eachVotePay); logger.debug("pay {} stand reward {}", Hex.toHexString(b.toByteArray()), pay); - delegationStore.addVoteReward(dynamicPropertiesStore - .getCurrentCycleNumber(), b.toByteArray(), pay); payReward(b.toByteArray(), pay); } } @@ -76,8 +74,6 @@ public void payStandbyWitness() { public void payBlockReward(byte[] witnessAddress, long value) { logger.debug("pay {} block reward {}", Hex.toHexString(witnessAddress), value); - long cycle = dynamicPropertiesStore.getCurrentCycleNumber(); - delegationStore.addBlockReward(cycle, witnessAddress, value); payReward(witnessAddress, value); } @@ -123,7 +119,6 @@ public void withdrawReward(byte[] address) { // endCycle = currentCycle; if (CollectionUtils.isEmpty(accountCapsule.getVotesList())) { - delegationStore.setRemark(endCycle, address); delegationStore.setBeginCycle(address, endCycle + 1); return; } diff --git a/chainbase/src/main/java/org/tron/core/store/DelegationStore.java b/chainbase/src/main/java/org/tron/core/store/DelegationStore.java index 6f497e4fa29..2590a516d8e 100644 --- a/chainbase/src/main/java/org/tron/core/store/DelegationStore.java +++ b/chainbase/src/main/java/org/tron/core/store/DelegationStore.java @@ -29,48 +29,6 @@ public BytesCapsule get(byte[] key) { return ArrayUtils.isEmpty(value) ? null : new BytesCapsule(value); } - public void addBlockReward(long cycle, byte[] address, long value) { - byte[] key = buildRewardBlockKey(cycle, address); - BytesCapsule bytesCapsule = get(key); - - if (bytesCapsule == null) { - put(key, new BytesCapsule(ByteArray.fromLong(value))); - } else { - put(key, new BytesCapsule(ByteArray - .fromLong(ByteArray.toLong(bytesCapsule.getData()) + value))); - } - } - - public long getBlockReward(long cycle, byte[] address) { - BytesCapsule bytesCapsule = get(buildRewardBlockKey(cycle, address)); - if (bytesCapsule == null) { - return 0L; - } else { - return ByteArray.toLong(bytesCapsule.getData()); - } - } - - public void addVoteReward(long cycle, byte[] address, long value) { - byte[] key = buildRewardVoteKey(cycle, address); - BytesCapsule bytesCapsule = get(key); - - if (bytesCapsule == null) { - put(key, new BytesCapsule(ByteArray.fromLong(value))); - } else { - put(key, new BytesCapsule(ByteArray - .fromLong(ByteArray.toLong(bytesCapsule.getData()) + value))); - } - } - - public long getVoteReward(long cycle, byte[] address) { - BytesCapsule bytesCapsule = get(buildRewardVoteKey(cycle, address)); - if (bytesCapsule == null) { - return 0L; - } else { - return ByteArray.toLong(bytesCapsule.getData()); - } - } - public void addReward(long cycle, byte[] address, long value) { byte[] key = buildRewardKey(cycle, address); BytesCapsule bytesCapsule = get(key); @@ -95,23 +53,6 @@ public void setBeginCycle(byte[] address, long number) { put(address, new BytesCapsule(ByteArray.fromLong(number))); } - public BytesCapsule getRemark(long cycle, byte[] address) { - return get(buildRemarkKey(cycle, address)); - } - - public void setLastWithdrawCycle(long cycle, byte[] address) { - put(buildLastWithdrawCycleKey(address), new BytesCapsule(ByteArray.fromLong(cycle))); - } - - public long getLastWithdrawCycle(byte[] address) { - BytesCapsule bytesCapsule = get(buildLastWithdrawCycleKey(address)); - return bytesCapsule == null ? REMARK : ByteArray.toLong(bytesCapsule.getData()); - } - - public void setRemark(long cycle, byte[] address) { - put(buildRemarkKey(cycle, address), new BytesCapsule(ByteArray.fromLong(REMARK))); - } - public long getBeginCycle(byte[] address) { BytesCapsule bytesCapsule = get(address); return bytesCapsule == null ? 0 : ByteArray.toLong(bytesCapsule.getData()); @@ -181,22 +122,6 @@ private byte[] buildRewardKey(long cycle, byte[] address) { return (cycle + "-" + Hex.toHexString(address) + "-reward").getBytes(); } - private byte[] buildRewardBlockKey(long cycle, byte[] address) { - return (cycle + "-" + Hex.toHexString(address) + "-block").getBytes(); - } - - private byte[] buildRewardVoteKey(long cycle, byte[] address) { - return (cycle + "-" + Hex.toHexString(address) + "-reward-vote").getBytes(); - } - - private byte[] buildRemarkKey(long cycle, byte[] address) { - return (cycle + "-" + Hex.toHexString(address) + "-remark").getBytes(); - } - - private byte[] buildLastWithdrawCycleKey(byte[] address) { - return ("lastWithdraw-" + Hex.toHexString(address)).getBytes(); - } - private byte[] buildAccountVoteKey(long cycle, byte[] address) { return (cycle + "-" + Hex.toHexString(address) + "-account-vote").getBytes(); } diff --git a/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java b/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java index 6255fce7b22..226f1c3c60d 100644 --- a/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java +++ b/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java @@ -143,7 +143,7 @@ public class DynamicPropertiesStore extends TronStoreWithRevoking private static final byte[] CURRENT_CYCLE_NUMBER = "CURRENT_CYCLE_NUMBER".getBytes(); private static final byte[] CHANGE_DELEGATION = "CHANGE_DELEGATION".getBytes(); private static final byte[] ALLOW_PBFT = "ALLOW_PBFT".getBytes(); - private static final byte[] CURRENT_CYCLE_TIMESTAMP = "CURRENT_CYCLE_TIMESTAMP".getBytes(); +// private static final byte[] CURRENT_CYCLE_TIMESTAMP = "CURRENT_CYCLE_TIMESTAMP".getBytes(); to be delete v4.1 private static final byte[] ALLOW_MARKET_TRANSACTION = "ALLOW_MARKET_TRANSACTION".getBytes(); private static final byte[] MARKET_SELL_FEE = "MARKET_SELL_FEE".getBytes(); @@ -1999,18 +1999,6 @@ public long getAllowAccountStateRoot() { () -> new IllegalArgumentException("not found ALLOW_ACCOUNT_STATE_ROOT")); } - public void saveCurrentCycleTiimeStamp(long timeStamp) { - this.put(CURRENT_CYCLE_TIMESTAMP, new BytesCapsule(ByteArray.fromLong(timeStamp))); - - } - - public long getCurrentCycleTimeStamp() { - return Optional.ofNullable(getUnchecked(CURRENT_CYCLE_TIMESTAMP)) - .map(BytesCapsule::getData) - .map(ByteArray::toLong) - .orElse(0L); - } - public boolean allowAccountStateRoot() { return getAllowAccountStateRoot() == 1; } diff --git a/common/src/main/java/org/tron/common/parameter/CommonParameter.java b/common/src/main/java/org/tron/common/parameter/CommonParameter.java index 1de18d35fa8..0ab934e4719 100644 --- a/common/src/main/java/org/tron/common/parameter/CommonParameter.java +++ b/common/src/main/java/org/tron/common/parameter/CommonParameter.java @@ -297,10 +297,6 @@ public class CommonParameter { @Getter @Setter public long allowMarketTransaction; //committee parameter - - // @Getter - // @Setter - // public long allowShieldedTransaction; //committee parameter // full node used this parameter to close shielded transaction @Getter @Setter @@ -376,9 +372,6 @@ public class CommonParameter { public boolean solidityNodeHttpEnable = true; @Getter @Setter - public boolean nodeHttpStatisticsSRRewardEnable = false; - @Getter - @Setter public int maxTransactionPendingSize; @Getter @Setter diff --git a/common/src/main/java/org/tron/core/Constant.java b/common/src/main/java/org/tron/core/Constant.java index 73fe1834c97..57190233df8 100644 --- a/common/src/main/java/org/tron/core/Constant.java +++ b/common/src/main/java/org/tron/core/Constant.java @@ -93,7 +93,6 @@ public class Constant { public static final String NODE_HTTP_SOLIDITY_PORT = "node.http.solidityPort"; public static final String NODE_HTTP_FULLNODE_ENABLE = "node.http.fullNodeEnable"; public static final String NODE_HTTP_SOLIDITY_ENABLE = "node.http.solidityEnable"; - public static final String NODE_HTTP_STATISTICS_SR_REWARD_SWITCH = "node.http.statisticsSRRewardSwitch"; public static final String NODE_HTTP_PBFT_PORT = "node.http.PBFTPort"; public static final String NODE_RPC_THREAD = "node.rpc.thread"; diff --git a/common/src/main/java/org/tron/core/exception/AddressNotFound.java b/common/src/main/java/org/tron/core/exception/AddressNotFound.java deleted file mode 100644 index c37768e9fc3..00000000000 --- a/common/src/main/java/org/tron/core/exception/AddressNotFound.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.tron.core.exception; - -public class AddressNotFound extends StoreException { - - public AddressNotFound() { - super(); - } - - public AddressNotFound(String message) { - super(message); - } -} diff --git a/common/src/main/java/org/tron/core/exception/InvalidAddress.java b/common/src/main/java/org/tron/core/exception/InvalidAddress.java deleted file mode 100644 index e08f0574517..00000000000 --- a/common/src/main/java/org/tron/core/exception/InvalidAddress.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.tron.core.exception; - -public class InvalidAddress extends StoreException { - - public InvalidAddress() { - super(); - } - - public InvalidAddress(String message) { - super(message); - } -} diff --git a/consensus/src/main/java/org/tron/consensus/dpos/MaintenanceManager.java b/consensus/src/main/java/org/tron/consensus/dpos/MaintenanceManager.java index 82d59e5dd39..614e23894c2 100644 --- a/consensus/src/main/java/org/tron/consensus/dpos/MaintenanceManager.java +++ b/consensus/src/main/java/org/tron/consensus/dpos/MaintenanceManager.java @@ -144,8 +144,6 @@ public void doMaintenance() { if (dynamicPropertiesStore.allowChangeDelegation()) { long nextCycle = dynamicPropertiesStore.getCurrentCycleNumber() + 1; dynamicPropertiesStore.saveCurrentCycleNumber(nextCycle); - dynamicPropertiesStore.saveCurrentCycleTiimeStamp(dynamicPropertiesStore - .getLatestBlockHeaderTimestamp()); consensusDelegate.getAllWitnesses().forEach(witness -> { delegationStore.setBrokerage(nextCycle, witness.createDbKey(), delegationStore.getBrokerage(witness.createDbKey())); diff --git a/framework/src/main/java/org/tron/core/Wallet.java b/framework/src/main/java/org/tron/core/Wallet.java index 8854cfde038..0ba04fb492a 100755 --- a/framework/src/main/java/org/tron/core/Wallet.java +++ b/framework/src/main/java/org/tron/core/Wallet.java @@ -2617,187 +2617,6 @@ public ProposalList getPaginatedProposalList(long offset, long limit) { return builder.build(); } - public List getVoteList(byte[] address, long cycle) { - long current = dbManager.getDynamicPropertiesStore() - .getCurrentCycleNumber(); - for (long i = cycle; i <= current; i++) { - AccountCapsule accountCapsule = dbManager.getDelegationStore() - .getAccountVote(i, address); - if (accountCapsule != null) { - return accountCapsule.getVotesList(); - } - BytesCapsule remark = dbManager.getDelegationStore() - .getRemark(i, address); - - if (remark != null) { - return null; - } - } - - return dbManager.getAccountStore() - .get(address) == null ? null : dbManager.getAccountStore() - .get(address).getVotesList(); - } - - public HashMap computeUnwithdrawReward(byte[] address) { - HashMap rewardMap = new HashMap<>(); - long beginCycle = dbManager.getDelegationStore() - .getLastWithdrawCycle(address); - long endCycle = dbManager.getDynamicPropertiesStore() - .getCurrentCycleNumber(); - if (address.length == 0) { - return rewardMap; - } - - for (long cycle = beginCycle + 1; cycle <= endCycle; cycle++) { - List voteList = getVoteList(address, cycle); - if (voteList != null) { - for (Vote vote : voteList) { - byte[] srAddress = vote.getVoteAddress().toByteArray(); - long totalReward = dbManager.getDelegationStore().getReward(cycle, srAddress); - long totalVote = dbManager.getDelegationStore() - .getWitnessVote(cycle, srAddress); - if (totalVote == DelegationStore.REMARK || totalVote == 0) { - continue; - } - long userVote = vote.getVoteCount(); - double voteRate = (double) userVote / totalVote; - String SR = StringUtil - .encode58Check(srAddress); - if (!rewardMap.containsKey(SR)) { - rewardMap.put(SR, (long) (voteRate * totalReward)); - } else { - long reward = rewardMap.get(SR) + (long) (voteRate * totalReward); - rewardMap.put(SR, reward); - } - } - } - } - return rewardMap; - } - - public HashMap computeRewardByCycle(byte[] address, - long beginCycle, long endCycle) { - HashMap rewardMap = new HashMap<>(); - if (address.length == 0) { - return rewardMap; - } - - for (long cycle = beginCycle; cycle <= endCycle; cycle++) { - List voteList = getVoteList(address, cycle); - if (voteList != null) { - for (Vote vote : voteList) { - byte[] srAddress = vote.getVoteAddress().toByteArray(); - long totalReward = dbManager.getDelegationStore().getReward(cycle, srAddress); - long totalVote = dbManager.getDelegationStore() - .getWitnessVote(cycle, srAddress); - if (totalVote == DelegationStore.REMARK || totalVote == 0) { - continue; - } - long userVote = vote.getVoteCount(); - double voteRate = (double) userVote / totalVote; - String SR = StringUtil - .encode58Check(srAddress); - - logger.debug("Account-userVote: {}, Account-totalVote: {},Account-SR: {},", - userVote, totalVote, SR); - - if (!rewardMap.containsKey(SR)) { - rewardMap.put(SR, (long) (voteRate * totalReward)); - } else { - long reward = rewardMap.get(SR) + (long) (voteRate * totalReward); - rewardMap.put(SR, reward); - } - } - } - } - logger.debug("Account-rewardMap: {}", - rewardMap); - return rewardMap; - } - - public HashMap queryPayByCycle(byte[] address, - long beginCycle, long endCycle) { - HashMap rewardMap = new HashMap<>(); - if (!dbManager.getDynamicPropertiesStore().allowChangeDelegation()) { - return rewardMap; - } - - AccountCapsule accountCapsule = dbManager.getAccountStore().get(address); - long reward = 0; - if (accountCapsule == null) { - return rewardMap; - } - - long blockPayReward = 0; - if (beginCycle <= endCycle) { - for (long cycle = beginCycle; cycle <= endCycle; cycle++) { - int brokerage = dbManager.getDelegationStore().getBrokerage(cycle, address); - blockPayReward += dbManager.getDelegationStore().getBlockReward(cycle, address); - if (brokerage == 100) { - reward += dbManager.getDelegationStore().getBlockReward(cycle, address) + dbManager - .getDelegationStore().getVoteReward(cycle, address); - } else { - double brokerageRate = (double) brokerage / 100; - reward += dbManager.getDelegationStore().getReward(cycle, address) / (1 - brokerageRate); - } - } - } - rewardMap.put("total", reward); - rewardMap.put("produceBlock", blockPayReward); - rewardMap.put("vote", reward - blockPayReward); - - return rewardMap; - } - - public double percentageOfBlockReward(long beginCycle, long endCycle, byte[] address) { - long reward = 0; - long blockPayReward = 0; - if (beginCycle <= endCycle) { - for (long cycle = beginCycle; cycle <= endCycle; cycle++) { - int brokerage = dbManager.getDelegationStore().getBrokerage(cycle, address); - if (brokerage == 100) { - continue; - } - - double brokerageRate = (double) brokerage / 100; - reward += dbManager.getDelegationStore().getReward(cycle, address) / (1 - brokerageRate); - blockPayReward += dbManager.getDelegationStore().getBlockReward(cycle, address); - } - } - - if (reward == 0 || blockPayReward == 0) { - return 0; - } - return (double) blockPayReward / (double) reward; - } - - public HashMap queryRewardByCycle(byte[] address, - long beginCycle, long endCycle) { - HashMap rewardMap = new HashMap<>(); - if (!dbManager.getDynamicPropertiesStore().allowChangeDelegation()) { - return rewardMap; - } - - AccountCapsule accountCapsule = dbManager.getAccountStore().get(address); - long bonus = 0; - if (accountCapsule == null) { - return rewardMap; - } - if (beginCycle <= endCycle) { - for (long cycle = beginCycle; cycle <= endCycle; cycle++) { - bonus += dbManager.getDelegationStore().getReward(cycle, address); - } - } - double percentage = percentageOfBlockReward(beginCycle, endCycle, address); - Double blockBonus = new Double(bonus * percentage); - - rewardMap.put("total", bonus); - rewardMap.put("produceBlock", blockBonus.longValue()); - rewardMap.put("vote", bonus - blockBonus.longValue()); - return rewardMap; - } - public ExchangeList getPaginatedExchangeList(long offset, long limit) { if (limit < 0 || offset < 0) { return null; @@ -2832,85 +2651,6 @@ public ExchangeList getPaginatedExchangeList(long offset, long limit) { } - public double queryVoteNumber(byte[] address, long beginCycle, long endCycle) { - - AccountCapsule accountCapsule = dbManager.getAccountStore().get(address); - long voteNumber = 0; - if (accountCapsule == null) { - return 0; - } - if (beginCycle <= endCycle) { - for (long cycle = beginCycle; cycle <= endCycle; cycle++) { - voteNumber += dbManager.getDelegationStore().getWitnessVote(cycle, address); - } - voteNumber = voteNumber / (endCycle - beginCycle + 1); - } - return voteNumber; - } - - public double queryTotalVoteNumber(long beginCycle, long endCycle) { - AtomicLong voteNumber = new AtomicLong(); - double voteNumberTotal = 0; - - if (beginCycle <= endCycle) { - for (long cycle = beginCycle; cycle <= endCycle; cycle++) { - List allWitnesses = dbManager.getWitnessStore().getAllWitnesses(); - long finalCycle = cycle; - allWitnesses.forEach(witness -> { - voteNumber.addAndGet(dbManager.getDelegationStore() - .getWitnessVote(finalCycle, witness.getAddress().toByteArray())); - }); - } - voteNumberTotal = voteNumber.doubleValue() / (double) (endCycle - beginCycle + 1); - } - return voteNumberTotal; - } - - public double querySrRatio(byte[] address, long beginCycle, long endCycle) { - AccountCapsule accountCapsule = dbManager.getAccountStore().get(address); - double borkerage = 0; - if (accountCapsule == null) { - return 0; - } - if (beginCycle <= endCycle) { - for (long cycle = beginCycle; cycle <= endCycle; cycle++) { - borkerage += dbManager.getDelegationStore().getBrokerage(cycle, address); - } - } - borkerage = borkerage / (endCycle - beginCycle + 1); - return 100 - borkerage; - } - - public long getRewardOfVoteEachBlock() { - return dbManager.getDynamicPropertiesStore().getWitness127PayPerBlock(); - } - - public long getRewardOfBlockEachBlock() { - return dbManager.getDynamicPropertiesStore().getWitnessPayPerBlock(); - } - - public int getSrNumber() { - return dbManager.getWitnessStore().getAllWitnesses().size(); - } - - public double queryNowVoteNumber(byte[] address) { - return dbManager.getWitnessStore().get(address).getVoteCount(); - } - - public double queryNowTotalVoteNumber() { - AtomicLong voteNumber = new AtomicLong(); - List allWitnesses = getStandbyWitness(); - allWitnesses.forEach(witness -> { - voteNumber.addAndGet(dbManager.getWitnessStore() - .get(witness.toByteArray()).getVoteCount()); - }); - return voteNumber.doubleValue(); - } - - public double queryNowSrRatio(byte[] address) { - return 100 - dbManager.getDelegationStore().getBrokerage(address); - } - /* * strip right 0 from memo */ @@ -3910,64 +3650,5 @@ public BytesMessage getTriggerInputForShieldedTRC20Contract( BytesMessage.Builder bytesBuilder = BytesMessage.newBuilder(); return bytesBuilder.setValue(ByteString.copyFrom(Hex.decode(input))).build(); } - - public double getBlockNumberEachDay() { - long maintenanceTimeInterval = CommonParameter.getInstance().getMaintenanceTimeInterval(); - if (maintenanceTimeInterval == 0) { - maintenanceTimeInterval = 21600000L; - } - double blockNumberEachDay = FROZEN_PERIOD / BLOCK_PRODUCED_INTERVAL - - 2 * (FROZEN_PERIOD / maintenanceTimeInterval); - return blockNumberEachDay; - } - - public double getAnnualizedRateOfReturn(long rewardOfBlockEachBlock, double blockNumberEachDay, - double srNumber, double srVote, double totalVote, - long rewardOfVoteEachBlock, double ratio) - throws Exception { - if ((int) srVote == 0) { - return 0; - } - if (totalVote < srVote || totalVote <= 0 || srVote <= 0 || ratio > 100 || ratio < 0) { - throw new Exception("bad parameters"); - } - double annualizedRateOfReturn = (rewardOfBlockEachBlock / srNumber / srVote - + rewardOfVoteEachBlock / totalVote) * blockNumberEachDay * ratio * 365; - return annualizedRateOfReturn; - } - - public boolean checkAddress(byte[] address) { - return consensusDelegate.getActiveWitnesses().contains(ByteString.copyFrom(address)); - } - - public boolean existAddress(byte[] address) { - WitnessCapsule witnessCapsule = dbManager.getWitnessStore().get(address); - if (witnessCapsule != null) { - return true; - } - return false; - } - - public List getStandbyWitness() { - List witnessAddressList = new ArrayList<>(); - for (WitnessCapsule witnessCapsule : consensusDelegate.getAllWitnesses()) { - witnessAddressList.add(witnessCapsule.getAddress()); - } - witnessAddressList.sort(Comparator.comparingLong((ByteString b) -> - consensusDelegate.getWitness(b.toByteArray()).getVoteCount()) - .reversed() - .thenComparing(Comparator.comparingInt(ByteString::hashCode).reversed())); - - if (witnessAddressList.size() > WITNESS_STANDBY_LENGTH) { - witnessAddressList = witnessAddressList.subList(0, WITNESS_STANDBY_LENGTH); - } - return witnessAddressList; - - } - - public boolean checkStandbyWitness(byte[] address) { - boolean contains = getStandbyWitness().contains(ByteString.copyFrom(address)); - return contains; - } } diff --git a/framework/src/main/java/org/tron/core/config/args/Args.java b/framework/src/main/java/org/tron/core/config/args/Args.java index bc96168171f..0623901114f 100644 --- a/framework/src/main/java/org/tron/core/config/args/Args.java +++ b/framework/src/main/java/org/tron/core/config/args/Args.java @@ -301,11 +301,6 @@ public static void setParam(final String[] args, final String confFileName) { PARAMETER.solidityNodeHttpEnable = config.getBoolean(Constant.NODE_HTTP_SOLIDITY_ENABLE); } - if (config.hasPath(Constant.NODE_HTTP_STATISTICS_SR_REWARD_SWITCH)) { - PARAMETER.nodeHttpStatisticsSRRewardEnable = config - .getBoolean(Constant.NODE_HTTP_STATISTICS_SR_REWARD_SWITCH); - } - if (config.hasPath(Constant.VM_MIN_TIME_RATIO)) { PARAMETER.minTimeRatio = config.getDouble(Constant.VM_MIN_TIME_RATIO); } diff --git a/framework/src/main/java/org/tron/core/services/http/FullNodeHttpApiService.java b/framework/src/main/java/org/tron/core/services/http/FullNodeHttpApiService.java index 27264a59542..8769d0c36eb 100644 --- a/framework/src/main/java/org/tron/core/services/http/FullNodeHttpApiService.java +++ b/framework/src/main/java/org/tron/core/services/http/FullNodeHttpApiService.java @@ -254,18 +254,6 @@ public class FullNodeHttpApiService implements Service { @Autowired private MetricsServlet metricsServlet; @Autowired - private GetAccountRewardByCycleServlet getAccountRewardByCycleServlet; - @Autowired - private GetSRProfitByCycleServlet getSRProfitByCycleServlet; - @Autowired - private GetSRDividendsByCycleServlet getSRDividendsByCycleServlet; - @Autowired - private GetAccountLastUnwithdrawRewardServlet getAccountLastUnwithdrawRewardServlet; - @Autowired - private GetCurrentCycleService getCurrentCycleServlet; - @Autowired - private GetNowSRAnnualizedRateOfReturnServlet getNowSRAnnualizedRateOfReturnServlet; - @Autowired private MarketSellAssetServlet marketSellAssetServlet; @Autowired private MarketCancelOrderServlet marketCancelOrderServlet; @@ -498,21 +486,6 @@ public void start() { context.addServlet(new ServletHolder(updateBrokerageServlet), "/wallet/updateBrokerage"); context.addServlet(new ServletHolder(createCommonTransactionServlet), "/wallet/createCommonTransaction"); - if (Args.getInstance().isNodeHttpStatisticsSRRewardEnable()) { - context.addServlet(new ServletHolder(getAccountRewardByCycleServlet), - "/wallet/getAccountRewardByCycleServlet"); - context.addServlet(new ServletHolder(getSRProfitByCycleServlet), - "/wallet/getSRProfitByCycleServlet"); - context.addServlet(new ServletHolder(getSRDividendsByCycleServlet), - "/wallet/getSRDividendsByCycleServlet"); - context.addServlet(new ServletHolder(getNowSRAnnualizedRateOfReturnServlet), - "/wallet/getNowSRAnnualizedRateOfReturnServlet"); - context.addServlet(new ServletHolder(getAccountLastUnwithdrawRewardServlet), - "/wallet/getAccountLastUnwithdrawRewardServlet"); - context.addServlet(new ServletHolder(getCurrentCycleServlet), - "/wallet/getCurrentCycleServlet"); - } - context.addServlet(new ServletHolder(getTransactionInfoByBlockNumServlet), "/wallet/gettransactioninfobyblocknum"); context.addServlet(new ServletHolder(listNodesServlet), "/net/listnodes"); diff --git a/framework/src/main/java/org/tron/core/services/http/GetAccountLastUnwithdrawRewardServlet.java b/framework/src/main/java/org/tron/core/services/http/GetAccountLastUnwithdrawRewardServlet.java deleted file mode 100644 index 77592dd26b2..00000000000 --- a/framework/src/main/java/org/tron/core/services/http/GetAccountLastUnwithdrawRewardServlet.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.tron.core.services.http; - -import java.io.IOException; -import java.util.HashMap; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; - -@Component -@Slf4j(topic = "API") -public class GetAccountLastUnwithdrawRewardServlet extends RateLimiterServlet { - - @Autowired - private Wallet wallet; - - protected void doGet(HttpServletRequest request, HttpServletResponse response) { - try { - byte[] address = Util.getAddress(request); - fillResponse(address, response); - } catch (Exception e) { - Util.processError(e, response); - } - } - - protected void doPost(HttpServletRequest request, HttpServletResponse response) { - try { - PostParams params = PostParams.getPostParams(request); - Account.Builder build = Account.newBuilder(); - JsonFormat.merge(params.getParams(), build, params.isVisible()); - fillResponse(build.getAddress().toByteArray(), response); - } catch (Exception e) { - Util.processError(e, response); - } - } - - private void fillResponse(byte[] address, HttpServletResponse response) throws IOException { - if (address != null) { - HashMap value = wallet - .computeUnwithdrawReward(address); - response.getWriter().println(Util.printRewardMapToJSON(value)); - } else { - response.getWriter().println("{}"); - } - } -} \ No newline at end of file diff --git a/framework/src/main/java/org/tron/core/services/http/GetAccountRewardByCycleServlet.java b/framework/src/main/java/org/tron/core/services/http/GetAccountRewardByCycleServlet.java deleted file mode 100644 index 5e3c6c356e9..00000000000 --- a/framework/src/main/java/org/tron/core/services/http/GetAccountRewardByCycleServlet.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.tron.core.services.http; - -import com.alibaba.fastjson.JSONObject; -import java.io.IOException; -import java.util.HashMap; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; - -@Component -@Slf4j(topic = "API") -public class GetAccountRewardByCycleServlet extends RateLimiterServlet { - - @Autowired - private Wallet wallet; - - protected void doGet(HttpServletRequest request, HttpServletResponse response) { - try { - byte[] address = Util.getAddress(request); - long startCycle = Long.parseLong(request.getParameter("startCycle")); - long endCycle = Long.parseLong(request.getParameter("endCycle")); - fillResponse(startCycle, endCycle, address, response); - } catch (Exception e) { - Util.processError(e, response); - } - } - - protected void doPost(HttpServletRequest request, HttpServletResponse response) { - try { - PostParams params = PostParams.getPostParams(request); - Account.Builder build = Account.newBuilder(); - JsonFormat.merge(params.getParams(), build, params.isVisible()); - JSONObject jsonObject = JSONObject.parseObject(params.getParams()); - long startCycle = jsonObject.getLong("startCycle"); - long endCycle = jsonObject.getLong("endCycle"); - fillResponse(startCycle, endCycle, build.getAddress().toByteArray(), response); - } catch (Exception e) { - Util.processError(e, response); - } - } - - private void fillResponse(long startCycle, long endCycle, byte[] address, - HttpServletResponse response) throws IOException { - if (startCycle <= endCycle && address != null) { - HashMap value = wallet.computeRewardByCycle(address, startCycle, endCycle); - response.getWriter().println(Util.printRewardMapToJSON(value)); - } else { - response.getWriter().println("{}"); - } - } -} \ No newline at end of file diff --git a/framework/src/main/java/org/tron/core/services/http/GetCurrentCycleService.java b/framework/src/main/java/org/tron/core/services/http/GetCurrentCycleService.java deleted file mode 100644 index 23f6514cf17..00000000000 --- a/framework/src/main/java/org/tron/core/services/http/GetCurrentCycleService.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.tron.core.services.http; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.tron.core.db.Manager; - -@Component -@Slf4j(topic = "API") -public class GetCurrentCycleService extends RateLimiterServlet { - - @Autowired - private Manager manager; - - protected void doGet(HttpServletRequest request, HttpServletResponse response) { - try { - long cycle = manager.getDynamicPropertiesStore() - .getCurrentCycleNumber(); - response.getWriter().println("{\"cycle\": " + cycle + "}"); - } catch (Exception e) { - Util.processError(e, response); - } - } - - protected void doPost(HttpServletRequest request, HttpServletResponse response) { - doGet(request, response); - } -} \ No newline at end of file diff --git a/framework/src/main/java/org/tron/core/services/http/GetNowSRAnnualizedRateOfReturnServlet.java b/framework/src/main/java/org/tron/core/services/http/GetNowSRAnnualizedRateOfReturnServlet.java deleted file mode 100644 index af0470dad30..00000000000 --- a/framework/src/main/java/org/tron/core/services/http/GetNowSRAnnualizedRateOfReturnServlet.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.tron.core.services.http; - -import static org.tron.core.config.Parameter.ChainConstant.MAX_ACTIVE_WITNESS_NUM; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.tron.common.utils.DecodeUtil; -import org.tron.core.Wallet; -import org.tron.core.exception.AddressNotFound; -import org.tron.core.exception.InvalidAddress; - -@Component -@Slf4j(topic = "API") -public class GetNowSRAnnualizedRateOfReturnServlet extends RateLimiterServlet { - - @Autowired - private Wallet wallet; - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) { - try { - double annualizedRateOfReturn = 0; - byte[] address = Util.getAddress(request); - if (!DecodeUtil.addressValid(address)) { - throw new InvalidAddress("Invalid address!"); - } - long rewardOfVoteEachBlock = wallet.checkStandbyWitness(address) - ? wallet.getRewardOfVoteEachBlock() / 1000000 : 0; - long rewardOfBlockEachBlock = wallet.checkAddress(address) - ? wallet.getRewardOfBlockEachBlock() / 1000000 : 0; - double srNumber = MAX_ACTIVE_WITNESS_NUM; - double blockNumberEachDay = wallet.getBlockNumberEachDay(); - double totalVote; - double srVote; - double ratio; - if (!wallet.existAddress(address)) { - throw new AddressNotFound("address not found!"); - } - srVote = wallet.queryNowVoteNumber(address); - totalVote = wallet.queryNowTotalVoteNumber(); - ratio = wallet.queryNowSrRatio(address); - annualizedRateOfReturn = wallet.getAnnualizedRateOfReturn(rewardOfBlockEachBlock, - blockNumberEachDay, srNumber, srVote, totalVote, rewardOfVoteEachBlock, ratio); - response.getWriter().println("{\"annualizedRateOfReturn\": " + annualizedRateOfReturn + "}"); - } catch (Exception e) { - Util.processError(e, response); - } - } - - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) { - try { - byte[] address = Util.getAddress(request); - if (!DecodeUtil.addressValid(address)) { - throw new InvalidAddress("Invalid address!"); - } - double annualizedRateOfReturn = 0; - long rewardOfVoteEachBlock = wallet.checkStandbyWitness(address) - ? wallet.getRewardOfVoteEachBlock() / 1000000 : 0; - long rewardOfBlockEachBlock = wallet.checkAddress(address) - ? wallet.getRewardOfBlockEachBlock() / 1000000 : 0; - double srNumber = MAX_ACTIVE_WITNESS_NUM; - double blockNumberEachDay = wallet.getBlockNumberEachDay(); - double totalVote; - double srVote; - double ratio; - if (!wallet.existAddress(address)) { - throw new AddressNotFound("address not found!"); - } - srVote = wallet.queryNowVoteNumber(address); - totalVote = wallet.queryNowTotalVoteNumber(); - ratio = wallet.queryNowSrRatio(address); - annualizedRateOfReturn = wallet.getAnnualizedRateOfReturn(rewardOfBlockEachBlock, - blockNumberEachDay, srNumber, srVote, totalVote, rewardOfVoteEachBlock, ratio); - response.getWriter().println("{\"annualizedRateOfReturn\": " + annualizedRateOfReturn + "}"); - } catch (Exception e) { - Util.processError(e, response); - } - } -} diff --git a/framework/src/main/java/org/tron/core/services/http/GetSRDividendsByCycleServlet.java b/framework/src/main/java/org/tron/core/services/http/GetSRDividendsByCycleServlet.java deleted file mode 100644 index 83d7735c330..00000000000 --- a/framework/src/main/java/org/tron/core/services/http/GetSRDividendsByCycleServlet.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.tron.core.services.http; - -import com.alibaba.fastjson.JSONObject; -import java.util.HashMap; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; - -@Component -@Slf4j(topic = "API") -public class GetSRDividendsByCycleServlet extends RateLimiterServlet { - - @Autowired - private Wallet wallet; - - protected void doGet(HttpServletRequest request, HttpServletResponse response) { - try { - byte[] address = Util.getAddress(request); - long startCycle = Long.parseLong(request.getParameter("startCycle")); - long endCycle = Long.parseLong(request.getParameter("endCycle")); - if (startCycle <= endCycle && address != null) { - HashMap value = wallet - .queryRewardByCycle(address, startCycle, endCycle); - response.getWriter().println(Util.printMapToJSON(value)); - } else { - response.getWriter().println("{}"); - } - } catch (Exception e) { - Util.processError(e, response); - } - } - - protected void doPost(HttpServletRequest request, HttpServletResponse response) { - try { - PostParams params = PostParams.getPostParams(request); - Account.Builder build = Account.newBuilder(); - JsonFormat.merge(params.getParams(), build, params.isVisible()); - JSONObject jsonObject = JSONObject.parseObject(params.getParams()); - long startCycle = jsonObject.getLong("startCycle"); - long endCycle = jsonObject.getLong("endCycle"); - byte[] address = build.getAddress().toByteArray(); - if (startCycle <= endCycle && address != null) { - HashMap value = wallet - .queryRewardByCycle(address, startCycle, endCycle); - response.getWriter().println(Util.printMapToJSON(value)); - } else { - response.getWriter().println("{}"); - } - } catch (Exception e) { - Util.processError(e, response); - } - } -} diff --git a/framework/src/main/java/org/tron/core/services/http/GetSRProfitByCycleServlet.java b/framework/src/main/java/org/tron/core/services/http/GetSRProfitByCycleServlet.java deleted file mode 100644 index 6c8c5f2e333..00000000000 --- a/framework/src/main/java/org/tron/core/services/http/GetSRProfitByCycleServlet.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.tron.core.services.http; - -import com.alibaba.fastjson.JSONObject; -import java.util.HashMap; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; - -@Component -@Slf4j(topic = "API") -public class GetSRProfitByCycleServlet extends RateLimiterServlet { - - @Autowired - private Wallet wallet; - - protected void doGet(HttpServletRequest request, HttpServletResponse response) { - try { - byte[] address = Util.getAddress(request); - long startCycle = Long.parseLong(request.getParameter("startCycle")); - long endCycle = Long.parseLong(request.getParameter("endCycle")); - if (startCycle <= endCycle && address != null) { - HashMap value = wallet - .queryPayByCycle(address, startCycle, endCycle); - response.getWriter().println(Util.printMapToJSON(value)); - } else { - response.getWriter().println("{}"); - } - } catch (Exception e) { - Util.processError(e, response); - } - } - - protected void doPost(HttpServletRequest request, HttpServletResponse response) { - try { - PostParams params = PostParams.getPostParams(request); - Account.Builder build = Account.newBuilder(); - JsonFormat.merge(params.getParams(), build, params.isVisible()); - JSONObject jsonObject = JSONObject.parseObject(params.getParams()); - long startCycle = jsonObject.getLong("startCycle"); - long endCycle = jsonObject.getLong("endCycle"); - byte[] address = build.getAddress().toByteArray(); - if (startCycle <= endCycle && address != null) { - HashMap value = wallet - .queryPayByCycle(address, startCycle, endCycle); - response.getWriter().println(Util.printMapToJSON(value)); - } else { - response.getWriter().println("{}"); - } - } catch (Exception e) { - Util.processError(e, response); - } - } -} diff --git a/framework/src/main/java/org/tron/core/services/http/Util.java b/framework/src/main/java/org/tron/core/services/http/Util.java index 2a762bfa379..1cc6c47ec35 100644 --- a/framework/src/main/java/org/tron/core/services/http/Util.java +++ b/framework/src/main/java/org/tron/core/services/http/Util.java @@ -89,25 +89,6 @@ public static String printBlock(Block block, boolean selfType) { return printBlockToJSON(block, selfType).toJSONString(); } - public static JSONObject printMapToJSON(HashMap map) { - JSONObject jsonObject = new JSONObject(); - for (HashMap.Entry entry : map.entrySet()) { - jsonObject.put(entry.getKey(), entry.getValue()); - } - return jsonObject; - } - - public static JSONObject printRewardMapToJSON(HashMap rewardMap) { - JSONObject jsonObject = new JSONObject(); - long totalReward = 0; - for (HashMap.Entry entry : rewardMap.entrySet()) { - jsonObject.put(entry.getKey(), entry.getValue()); - totalReward += entry.getValue(); - } - jsonObject.put("totalReward", totalReward); - return jsonObject; - } - public static JSONObject printBlockToJSON(Block block, boolean selfType) { BlockCapsule blockCapsule = new BlockCapsule(block); String blockID = ByteArray.toHexString(blockCapsule.getBlockId().getBytes()); diff --git a/framework/src/test/java/org/tron/core/WalletTest.java b/framework/src/test/java/org/tron/core/WalletTest.java index 6eaf91e374b..71d2b2a4c81 100644 --- a/framework/src/test/java/org/tron/core/WalletTest.java +++ b/framework/src/test/java/org/tron/core/WalletTest.java @@ -525,127 +525,5 @@ public void testChainParameters() { System.out.printf(builder.build().toString()); } - @Test - public void getRewardOfVoteEachBlock() { - long l = wallet.getRewardOfVoteEachBlock(); - System.out.println(l); - assertEquals(16000000L, l); - } - - @Test - public void getRewardOfBlockEachBlock() { - long l = wallet.getRewardOfBlockEachBlock(); - assertEquals(32000000L, l); - } - - @Test - public void queryVoteNumberZero() { - double v = wallet.queryVoteNumber(ACCOUNT_ADDRESS_ONE.getBytes(), - CYCLE_NUM_ONE, CYCLE_NUM_TWO); - assertEquals(0.0, v, 0); - } - - @Test - public void queryTotalVoteNumber() { - double v = wallet.queryTotalVoteNumber(CYCLE_NUM_ONE, CYCLE_NUM_ONE); - int srNumber = wallet.getSrNumber(); - assertEquals(-srNumber, v, 0); - } - - @Test - public void getBlockNumberEachDay() { - double v = wallet.getBlockNumberEachDay(); - assertEquals(28792, v, 0); - } - - @Test - public void getAnnualizedRateOfReturn() throws Exception { - double v = wallet.getAnnualizedRateOfReturn(1, 1, - 1, 1, 1, 1, 1); - assertEquals(730, v, 0); - double v1 = wallet.getAnnualizedRateOfReturn(1, 1, - 1, 0, 1, 1, 1); - assertEquals(0, v1, 0); - } - - @Test - public void getVoteList() { - long currentcycle = 10; - String OWNER_ADDRESS = - Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; - - AccountCapsule ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), - ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), AccountType.Normal, - 110_000_000L); - chainBaseManager.getDelegationStore() - .setAccountVote(currentcycle, ACCOUNT_ADDRESS_ONE.getBytes(), ownerCapsule); - chainBaseManager.getDynamicPropertiesStore() - .saveCurrentCycleNumber(currentcycle + 10); - - Assert.assertNotNull( - wallet.getVoteList(ACCOUNT_ADDRESS_ONE.getBytes(), currentcycle)); - Assert.assertNull( - wallet.getVoteList(ACCOUNT_ADDRESS_ONE.getBytes(), currentcycle + 1)); - Assert.assertNotNull( - wallet.getVoteList(ACCOUNT_ADDRESS_ONE.getBytes(), currentcycle - 1)); - } - - @Test - public void testQueryPayByCycle() { - String OWNER_ADDRESS = - Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; - long start = 10; - long end = start + 60; - { - chainBaseManager.getDynamicPropertiesStore().saveChangeDelegation(0); - assertEquals(wallet.queryPayByCycle(OWNER_ADDRESS - .getBytes(), start, end).size(), 0); - } - { - chainBaseManager.getDynamicPropertiesStore().saveChangeDelegation(1); - assertEquals(wallet.queryPayByCycle(OWNER_ADDRESS - .getBytes(), start, end).size(), 0); - } - { - AccountCapsule ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), - ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), AccountType.Normal, - 110_000_000L); - chainBaseManager.getAccountStore().put(OWNER_ADDRESS - .getBytes(), ownerCapsule); - Assert.assertNotEquals(wallet.queryPayByCycle(OWNER_ADDRESS - .getBytes(), start, end).size(), 0); - } - } - - @Test - public void testPercentageOfBlockReward() { - String OWNER_ADDRESS = - Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; - long beginCycle = 60; - long endCycle = 10; - double result = 0; - assertEquals(wallet.percentageOfBlockReward(beginCycle, endCycle, OWNER_ADDRESS - .getBytes()), result, 10); - } - - @Test - public void checkAddress() { - List witnessAddresses = new ArrayList<>(); - byte[] address = decode58Check("TT1smsmhxype64boboU8xTuNZVCKP1w6qT"); - witnessAddresses.add(ByteString.copyFrom(address)); - chainBaseManager.getWitnessScheduleStore().saveActiveWitnesses(witnessAddresses); - Assert.assertTrue(wallet.checkAddress(address)); - } - - @Test - public void existAddress() { - byte[] address = decode58Check("TT1smsmhxype64boboU8xTuNZVCKP1w6qT"); - byte[] address1 = decode58Check("TB4B1RMhoPeivkj4Hebm6tttHjRY9yQFes"); - WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(address)); - chainBaseManager.getWitnessStore().put(address, witnessCapsule); - Assert.assertTrue(wallet.existAddress(address)); - Assert.assertFalse(wallet.existAddress(address1)); - } - } diff --git a/framework/src/test/java/org/tron/core/services/DelegationServiceTest.java b/framework/src/test/java/org/tron/core/services/DelegationServiceTest.java index c66ab877194..c8a9f89acea 100644 --- a/framework/src/test/java/org/tron/core/services/DelegationServiceTest.java +++ b/framework/src/test/java/org/tron/core/services/DelegationServiceTest.java @@ -115,16 +115,5 @@ public void test() { manager.getDelegationStore().setWitnessVote(2, sr27, 100000000); testPay(0); testWithdraw(); - testBlockReward(); - } - - public void testBlockReward() { - String address = "TLTDZBcPoJ8tZ6TTEeEqEvwYFk2wgotSfD"; - long cycle = 10; - manager.getDelegationStore().addBlockReward(cycle, address.getBytes(), 10); - manager.getDelegationStore().addBlockReward(cycle, address.getBytes(), 20); - Assert.assertEquals(manager.getDelegationStore() - .getBlockReward(cycle, address.getBytes()), 30); - } } diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java index ca834546af6..52bf514c9f8 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java +++ b/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java @@ -156,33 +156,6 @@ public static HttpResponse voteWitnessAccount(String httpNode, byte[] ownerAddre return response; } - /** - * constructor. - */ - public static HttpResponse voteWitnessAccount(String httpNode, String ownerAddress, - JsonArray voteArray, String fromKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/votewitnessaccount"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("owner_address", ownerAddress); - userBaseObj2.add("votes", voteArray); - userBaseObj2.addProperty("visible", true); - logger.info(userBaseObj2.toString()); - response = createConnect(requestUrl, userBaseObj2); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, fromKey); - logger.info(transactionString); - logger.info(transactionSignString); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** * constructor. */ @@ -227,30 +200,6 @@ public static HttpResponse createWitness(String httpNode, byte[] ownerAddress, S return response; } - /** - * constructor. - */ - public static HttpResponse createWitness(String httpNode, byte[] ownerAddress, String url, - String ownerKey) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createwitness"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("url", str2hex(url)); - userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress)); - response = createConnect(requestUrl, userBaseObj2); - logger.info(userBaseObj2.toString()); - transactionString = EntityUtils.toString(response.getEntity()); - transactionSignString = gettransactionsign(httpNode, transactionString, ownerKey); - response = broadcastTransaction(httpNode, transactionSignString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** * constructor. */ @@ -4627,130 +4576,4 @@ public static HttpResponse getBrokerageFromPbft(String httpSolidityNode, byte[] return response; } - /** - * constructor. - */ - public static HttpResponse getCurrentCycle(String httpNode) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/getCurrentCycleServlet"; - JsonObject userBaseObj2 = new JsonObject(); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getNowSrAnnualizedRate(String httpNode, String address) { - try { - final String requestUrl = - "http://" + httpNode + "/wallet/getNowSRAnnualizedRateOfReturnServlet"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", address); - logger.info(address); - userBaseObj2.addProperty("visible", true); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getAccountRewardByCycle(String httpNode, String address, - Integer startCycle, Integer endCycle) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/getAccountRewardByCycleServlet"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", address); - logger.info(address); - userBaseObj2.addProperty("startCycle", String.valueOf(startCycle)); - userBaseObj2.addProperty("endCycle", String.valueOf(endCycle)); - userBaseObj2.addProperty("visible", true); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getAccountLastUnwithdrawReward(String httpNode, String address) { - try { - final String requestUrl = - "http://" + httpNode + "/wallet/getAccountLastUnwithdrawRewardServlet"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", address); - logger.info(address); - userBaseObj2.addProperty("visible", true); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse getSrProfitByCycle(String httpNode, String address, Integer startCycle, - Integer endCycle) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/getSRProfitByCycleServlet"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", address); - logger.info(address); - userBaseObj2.addProperty("visible", true); - userBaseObj2.addProperty("startCycle", String.valueOf(startCycle)); - userBaseObj2.addProperty("endCycle", String.valueOf(endCycle)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getSrDividendsByCycle(String httpNode, String address, - Integer startCycle, Integer endCycle) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/getSRDividendsByCycleServlet"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", address); - logger.info(address); - userBaseObj2.addProperty("visible", true); - userBaseObj2.addProperty("startCycle", String.valueOf(startCycle)); - userBaseObj2.addProperty("endCycle", String.valueOf(endCycle)); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - } diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpSrReward.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpSrReward.java deleted file mode 100644 index 7fb2bf4a43d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpSrReward.java +++ /dev/null @@ -1,163 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpSrReward { - - private final String foundationAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] foundationAddressByte = PublicMethed.getFinalAddress(foundationAccountKey); - private final String srKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final String srAddress = PublicMethed.getAddressString(srKey); - Long totalReward = 0L; - Integer cycle = 0; - Long amount = 50000000L; - Long frozenAmount = amount / 2; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - String voteAccountKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private final String voteAccountAddress = PublicMethed.getAddressString(voteAccountKey); - private final byte[] voteAccountAddressByte = PublicMethed.getFinalAddress(voteAccountKey); - JsonArray voteKeys = new JsonArray(); - JsonObject voteElement = new JsonObject(); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - - /** - * constructor. - */ - @Test(enabled = true, description = "Get now current cycles") - public void test01GetnowCurrentCycles() { - Integer retryTime = 100; - while (cycle < 3 && retryTime-- > 0) { - response = HttpMethed.getCurrentCycle(httpnode); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - cycle = responseContent.getInteger("cycle"); - HttpMethed.waitToProduceOneBlock(httpnode); - } - Assert.assertTrue(cycle >= 3); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get account reward by cycles") - public void test02GetAccountReward() throws Exception { - response = HttpMethed.sendCoin(httpnode, foundationAddressByte, voteAccountAddressByte, amount, - foundationAccountKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - //Freeze balance - response = HttpMethed - .freezeBalance(httpnode, voteAccountAddressByte, frozenAmount, 0, - 0, voteAccountKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - voteElement.addProperty("vote_address", srAddress); - voteElement.addProperty("vote_count", frozenAmount / 1000000L); - voteKeys.add(voteElement); - response = HttpMethed - .voteWitnessAccount(httpnode, voteAccountAddress, voteKeys, voteAccountKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - Integer retryTime = 50; - while (totalReward == 0 && retryTime-- > 0) { - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed - .getAccountRewardByCycle(httpnode, voteAccountAddress, cycle, cycle + 3); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - totalReward = responseContent.getLong("totalReward"); - } - Assert.assertTrue(totalReward > 0); - System.out.println("totalReward:" + totalReward); - System.out.println("responseContent.getLong(srAddress):" + responseContent.getLong(srAddress)); - //Assert.assertTrue(totalReward == responseContent.getLong(srAddress)); - Assert.assertEquals(totalReward, responseContent.getLong(srAddress)); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get account last unwithdraw reward") - public void test03GetAccountLastUnwithdrawReward() throws Exception { - response = HttpMethed - .getAccountLastUnwithdrawReward(httpnode, voteAccountAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Long unWithdrawReward = responseContent.getLong("totalReward"); - logger.info("unWithdrawReward:" + unWithdrawReward); - Assert.assertTrue(unWithdrawReward >= totalReward); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get SR profit by cycle") - public void test04GetSrProfitByCycle() throws Exception { - response = HttpMethed - .getSrProfitByCycle(httpnode, srAddress, cycle - 1, cycle + 2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Long total = responseContent.getLong("total"); - Long produceBlock = responseContent.getLong("produceBlock"); - Long vote = responseContent.getLong("vote"); - Assert.assertTrue(total == produceBlock + vote); - Assert.assertTrue(total > 0 && produceBlock > 0 && vote > 0); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Get SR dividends by cycle") - public void test05GetSrDividendsByCycle() throws Exception { - response = HttpMethed - .getSrDividendsByCycle(httpnode, srAddress, cycle - 1, cycle + 2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Long total = responseContent.getLong("total"); - Long produceBlock = responseContent.getLong("produceBlock"); - Long vote = responseContent.getLong("vote"); - Assert.assertTrue(total == produceBlock + vote); - Assert.assertTrue(total > 0 && produceBlock > 0 && vote > 0); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get now SR annualized rate") - public void test06GetNowSrAnnualizedRate() throws Exception { - response = HttpMethed.getNowSrAnnualizedRate(httpnode, srAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getDouble("annualizedRateOfReturn") > 0); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.unFreezeBalance(httpnode, voteAccountAddressByte, 0, voteAccountKey); - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestQueryReward001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestQueryReward001.java deleted file mode 100644 index 588054d1677..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestQueryReward001.java +++ /dev/null @@ -1,161 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; -import static org.tron.core.config.Parameter.ChainConstant.FROZEN_PERIOD; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestQueryReward001 { - - private final String foundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] foundationAddress = PublicMethed.getFinalAddress(foundationKey); - private final String foundationAddressString = Base58.encode58Check(PublicMethed - .getFinalAddress(foundationKey)); - private final String witnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress = PublicMethed.getFinalAddress(witnessKey); - private final String witnessAddressString = Base58.encode58Check(PublicMethed - .getFinalAddress(witnessKey)); - private JSONObject responseContent; - private JSONObject accountReward; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list") - .get(0); - Integer cycle = 0; - - /** - * constructor. - */ - @BeforeSuite(enabled = true) - public void beforeSuite() { - HttpMethed.sendCoin(httpnode,foundationAddress,witnessAddress,50000000L,foundationKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.freezeBalance(httpnode,witnessAddress,30000000L,3,0,witnessKey); - HttpMethed.waitToProduceOneBlock(httpnode); - JsonArray voteKeys = new JsonArray(); - JsonObject voteElement = new JsonObject(); - voteElement.addProperty("vote_address", Base58.encode58Check(PublicMethed - .getFinalAddress(witnessKey))); - voteElement.addProperty("vote_count", 20); - voteKeys.add(voteElement); - HttpMethed.voteWitnessAccount(httpnode, Base58.encode58Check(PublicMethed - .getFinalAddress(witnessKey)), voteKeys, witnessKey); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get account reward") - public void test01GetAccountReward() { - response = HttpMethed.getCurrentCycle(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - cycle = responseContent.getInteger("cycle"); - while (cycle < 2) { - response = HttpMethed.getCurrentCycle(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - cycle = responseContent.getInteger("cycle"); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - } - - response = HttpMethed - .getAccountRewardByCycle(httpnode, witnessAddressString, - 0, cycle + 1); - accountReward = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(accountReward); - Assert.assertTrue(accountReward.getLong("totalReward") > 0); - Assert.assertEquals(accountReward.getLong(witnessAddressString), - accountReward.getLong("totalReward")); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get llast unwithdraw account reward") - public void test02GetLastUnwithdrawAccountReward() { - response = HttpMethed - .getAccountLastUnwithdrawReward(httpnode, witnessAddressString); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getLong("totalReward") > 0); - Assert.assertEquals(responseContent.getLong(witnessAddressString), - responseContent.getLong("totalReward")); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get SR profit by cycle") - public void test03GetSrProfitByCycle() throws Exception { - response = HttpMethed - .getSrProfitByCycle(httpnode, witnessAddressString, 0, cycle + 2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Long total = responseContent.getLong("total"); - Long produceBlock = responseContent.getLong("produceBlock"); - Long vote = responseContent.getLong("vote"); - Assert.assertTrue(total == produceBlock + vote); - Assert.assertTrue(total > 0); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get SR dividends by cycle") - public void test04GetSrDividendsByCycle() throws Exception { - response = HttpMethed - .getSrDividendsByCycle(httpnode, witnessAddressString, 0, cycle + 2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Long total = responseContent.getLong("total"); - Long produceBlock = responseContent.getLong("produceBlock"); - Long vote = responseContent.getLong("vote"); - Assert.assertTrue(total == produceBlock + vote); - Assert.assertTrue(total > 0 && produceBlock > 0 && vote > 0); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get now SR annualized rate") - public void test05GetNowSrAnnualizedRate() throws Exception { - response = HttpMethed.getNowSrAnnualizedRate(httpnode, witnessAddressString); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getDouble("annualizedRateOfReturn") > 0); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.disConnect(); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TestApproveProposal.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TestApproveProposal.java index bf9fad62177..193d2a5f96f 100644 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TestApproveProposal.java +++ b/framework/src/test/java/stest/tron/wallet/onlinestress/TestApproveProposal.java @@ -62,11 +62,6 @@ public class TestApproveProposal { .get(0); private String soliditynode = Configuration.getByPath("testng.conf") .getStringList("solidityNode.ip.list").get(0); - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - JsonArray voteKeys = new JsonArray(); - JsonObject voteElement = new JsonObject(); - @BeforeSuite public void beforeSuite() { @@ -134,35 +129,6 @@ public void testApproveProposal() { } } - @Test(enabled = true) - public void testCreateWitness() { - int index = 2; - - while (index <= 27) { - String witnessKey = Configuration.getByPath("testng.conf") - .getString("mainWitness.key" + index); - byte[] witnessAddressByte = PublicMethed.getFinalAddress(witnessKey); - String witnessAddress = PublicMethed.getAddressString(witnessKey); - HttpMethed.sendCoin(httpnode, fromAddress, witnessAddressByte, 10100000000L, testKey002); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed - .createWitness(httpnode, witnessAddressByte, "Sr reward witness " + index, witnessKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.freezeBalance(httpnode, witnessAddressByte, 50000000L, 0, 0, witnessKey); - HttpMethed.waitToProduceOneBlock(httpnode); - - JsonArray voteKeys = new JsonArray(); - JsonObject voteElement = new JsonObject(); - voteElement.addProperty("vote_address", witnessAddress); - voteElement.addProperty("vote_count", index); - voteKeys.add(voteElement); - HttpMethed.voteWitnessAccount(httpnode, witnessAddress, voteKeys, witnessKey); - index++; - } - - } - - @Test(enabled = true) public void testGetChainParameters() { //Set the default map diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TestSrRewardOnlineData.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TestSrRewardOnlineData.java deleted file mode 100644 index a896537cea0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TestSrRewardOnlineData.java +++ /dev/null @@ -1,216 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; -import static org.tron.core.config.Parameter.ChainConstant.FROZEN_PERIOD; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import io.grpc.ManagedChannel; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.HttpMethed; - -@Slf4j -public class TestSrRewardOnlineData { - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String httpnode = "101.200.46.37:50191"; - private JSONObject responseContent; - private HttpResponse response; - Integer cycle = 0; - String srAddress = "TLyqzVGLV1srkB7dToTAEqgDSfPtXRJZYH"; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - - @Test(enabled = true) - public void test01GetAccountReward() { - response = HttpMethed.getCurrentCycle(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - cycle = responseContent.getInteger("cycle"); - - response = HttpMethed - .getAccountRewardByCycle(httpnode, "TWjvFoH2HgkNCsf897tG5BSzx7ZpfkqHPs", - cycle - 20, cycle + 1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - Long total = 0L; - Long totalReward = 0L; - for (Map.Entry entry : responseContent.entrySet()) { - if (entry.getKey() == "totalReward") { - totalReward = Long.valueOf(String.valueOf(entry.getValue())); - continue; - } - total = total + Long.valueOf(String.valueOf(entry.getValue())); - } - - logger.info("total :" + total); - logger.info("totalReward:" + totalReward); - } - - - @Test(enabled = true) - public void test02GetLastUnwithdrawAccountReward() { - response = HttpMethed - .getAccountLastUnwithdrawReward(httpnode, "TWjvFoH2HgkNCsf897tG5BSzx7ZpfkqHPs"); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Long unWithdrawReward = responseContent.getLong("totalReward"); - logger.info("unWithdrawReward:" + unWithdrawReward); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Get SR profit by cycle") - public void test03GetSrProfitByCycle() throws Exception { - response = HttpMethed - .getSrProfitByCycle(httpnode, srAddress, 0, cycle + 2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Long total = responseContent.getLong("total"); - Long produceBlock = responseContent.getLong("produceBlock"); - Long vote = responseContent.getLong("vote"); - Assert.assertTrue(total == produceBlock + vote); - - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Get SR dividends by cycle") - public void test04GetSrDividendsByCycle() throws Exception { - response = HttpMethed - .getSrDividendsByCycle(httpnode, srAddress, 0, cycle + 2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Long total = responseContent.getLong("total"); - Long produceBlock = responseContent.getLong("produceBlock"); - Long vote = responseContent.getLong("vote"); - Assert.assertTrue(total == produceBlock + vote); - //Assert.assertTrue(total > 0 && produceBlock > 0 && vote > 0); - //410BE88A918D74D0DFD71DC84BD4ABF036D0562991 - //TB4B1RMhoPeivkj4Hebm6tttHjRY9yQFes - //{ - //"address": "410BE88A918D74D0DFD71DC84BD4ABF036D0562991", - //"visible": false, - //"startCycle": "0", - // "endCycle": "888" - //} - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Get now SR annualized rate") - public void test05GetNowSrAnnualizedRate() throws Exception { - response = HttpMethed.getNowSrAnnualizedRate(httpnode, srAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getDouble("annualizedRateOfReturn") > 0); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Get now SR annualized rate") - public void test06GetNowSrAnnualizedRate() throws Exception { - response = HttpMethed.listwitnesses(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray wintessArray = responseContent.getJSONArray("witnesses"); - List voteList = new ArrayList<>(); - HashMap witness127 = new HashMap<>(); - - for (int i = 0; i < wintessArray.size(); i++) { - if (wintessArray.getJSONObject(i).containsKey("voteCount")) { - voteList.add(wintessArray.getJSONObject(i).getLong("voteCount")); - witness127.put(wintessArray.getJSONObject(i).getString("address"), - wintessArray.getJSONObject(i).getLong("voteCount")); - } - } - - Long totalVote = 0L; - Long voteFor127 = 0L; - - for (int j = 0; j < voteList.size(); j++) { - totalVote = totalVote + voteList.get(j); - if (j < 127) { - voteFor127 = voteFor127 + voteList.get(j); - } - } - - logger.info("totalVote :" + totalVote); - logger.info("voteFor127:" + voteFor127); - - double blockNumberEachDay = FROZEN_PERIOD / BLOCK_PRODUCED_INTERVAL - - 2 * (FROZEN_PERIOD / 21600000L); - - List result = new ArrayList<>(); - - for (String key : witness127.keySet()) { - Long srVote = witness127.get(key); - String witnessAddress = key; - response = HttpMethed.getNowSrAnnualizedRate(httpnode, witnessAddress); - responseContent = HttpMethed.parseResponseContent(response); - double annualizedRateOfReturn = Double.valueOf(responseContent - .getString("annualizedRateOfReturn")); - if (annualizedRateOfReturn > 0) { - result.add( - witnessAddress + " annualizedRateOfReturn is:" - + responseContent.getString("annualizedRateOfReturn")); - } - } - - for (int i = 0; i < result.size(); i++) { - logger.info(result.get(i)); - } - - logger.info(result.size() + ""); - - - - /* double annualizedRateOfReturn = ((double) 16 / (double) 27 / (double)srVote - + (double)160 / (double)voteFor127) * (double)blockNumberEachDay - * (double)80 * (double)365; - logger.info("voteFor127 annu is:" + annualizedRateOfReturn);*/ - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.disConnect(); - } - - -} - - - From 2acfab27b289f0d30349f24b6e149ddd8f923eb0 Mon Sep 17 00:00:00 2001 From: yhrzpm Date: Mon, 19 Oct 2020 18:54:58 +0800 Subject: [PATCH 35/60] log context when khaosDatabase throw npe and fix a unsafe-thread issue (#3450) Co-authored-by: Matt --- .../java/org/tron/core/db/KhaosDatabase.java | 47 +++++++++++++++---- .../main/java/org/tron/core/db/Manager.java | 11 ++++- 2 files changed, 48 insertions(+), 10 deletions(-) diff --git a/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java b/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java index 85bb1c9c40e..2676383052a 100644 --- a/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java +++ b/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java @@ -10,9 +10,11 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import java.util.stream.Stream; import lombok.Getter; +import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -26,6 +28,7 @@ import org.tron.core.exception.UnLinkedBlockException; @Component +@Slf4j(topic = "DB") public class KhaosDatabase extends TronDatabase { private KhaosBlock head; @@ -86,7 +89,7 @@ public Boolean containBlockInMiniStore(Sha256Hash hash) { } /** - * Get the Block form KhoasDB, if it doesn't exist ,return null. + * Get the Block from KhoasDB, if it doesn't exist ,return null. */ public BlockCapsule getBlock(Sha256Hash hash) { return Stream.of(miniStore.getByHash(hash), miniUnlinkedStore.getByHash(hash)) @@ -112,6 +115,11 @@ public BlockCapsule push(BlockCapsule blk) block.setParent(kblock); } else { miniUnlinkedStore.insert(block); + logger.error("blk:{}, head:{}, miniStore:{}, miniUnlinkedStore:{}", + blk, + head, + miniStore, + miniUnlinkedStore); throw new UnLinkedBlockException(); } } @@ -286,11 +294,21 @@ public int hashCode() { return Objects.hash(id); } + + @Override + public String toString() { + return "KhaosBlock{" + + "blk=" + blk + + ", parent=" + (parent == null ? null : parent.get()) + + ", id=" + id + + ", num=" + num + + '}'; + } } public class KhaosStore { - private HashMap hashKblkMap = new HashMap<>(); + private Map hashKblkMap = new ConcurrentHashMap<>(); // private HashMap parentHashKblkMap = new HashMap<>(); private int maxCapacity = 1024; @@ -307,23 +325,26 @@ protected boolean removeEldestEntry(Map.Entry> entry minNumMap.forEach((k, v) -> { numKblkMap.remove(k); - v.forEach(b -> hashKblkMap.remove(b.id)); + v.forEach(b -> { + hashKblkMap.remove(b.id); + logger.info("remove from khaosDatabase:{}", b.id); + }); }); return false; } }; - public void setMaxCapcity(int maxCapacity) { + public synchronized void setMaxCapcity(int maxCapacity) { this.maxCapacity = maxCapacity; } - public void insert(KhaosBlock block) { + public synchronized void insert(KhaosBlock block) { hashKblkMap.put(block.id, block); numKblkMap.computeIfAbsent(block.num, listBlk -> new ArrayList<>()).add(block); } - public boolean remove(Sha256Hash hash) { + public synchronized boolean remove(Sha256Hash hash) { KhaosBlock block = this.hashKblkMap.get(hash); // Sha256Hash parentHash = Sha256Hash.ZERO_HASH; if (block != null) { @@ -344,17 +365,25 @@ public boolean remove(Sha256Hash hash) { return false; } - public List getBlockByNum(Long num) { + public synchronized List getBlockByNum(Long num) { return numKblkMap.get(num); } - public KhaosBlock getByHash(Sha256Hash hash) { + public synchronized KhaosBlock getByHash(Sha256Hash hash) { return hashKblkMap.get(hash); } - public int size() { + public synchronized int size() { return hashKblkMap.size(); } + @Override + public String toString() { + return "KhaosStore{" + + "hashKblkMap=" + hashKblkMap + + ", maxCapacity=" + maxCapacity + + ", numKblkMap=" + numKblkMap + + '}'; + } } } diff --git a/framework/src/main/java/org/tron/core/db/Manager.java b/framework/src/main/java/org/tron/core/db/Manager.java index 5d797a68caa..d62373e22eb 100644 --- a/framework/src/main/java/org/tron/core/db/Manager.java +++ b/framework/src/main/java/org/tron/core/db/Manager.java @@ -898,7 +898,16 @@ public synchronized void pushBlock(final BlockCapsule block) "shielded transaction count > " + SHIELDED_TRANS_IN_BLOCK_COUNTS); } - BlockCapsule newBlock = this.khaosDb.push(block); + BlockCapsule newBlock; + try { + newBlock = this.khaosDb.push(block); + } catch (UnLinkedBlockException e) { + logger.error("latestBlockHeaderHash:{}, latestBlockHeaderNumber:{}, latestSolidifiedBlockNum:{}", + getDynamicPropertiesStore().getLatestBlockHeaderHash(), + getDynamicPropertiesStore().getLatestBlockHeaderNumber(), + getDynamicPropertiesStore().getLatestSolidifiedBlockNum()); + throw e; + } // DB don't need lower block if (getDynamicPropertiesStore().getLatestBlockHeaderHash() == null) { From bedd983b47d863201a1c3d050524600388b6297e Mon Sep 17 00:00:00 2001 From: xiangdepeng Date: Thu, 22 Oct 2020 15:34:58 +0800 Subject: [PATCH 36/60] delete ALLOW_TVM_STAKE proposal --- .../org/tron/core/utils/ProposalUtil.java | 24 +++++++++---------- .../tron/core/consensus/ProposalService.java | 8 +++---- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java b/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java index 4319ee5ee16..e1a299989a3 100644 --- a/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java +++ b/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java @@ -339,17 +339,17 @@ public static void validator(DynamicPropertiesStore dynamicPropertiesStore, } break; } - case ALLOW_TVM_STAKE: { - if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_1)) { - throw new ContractValidateException( - "Bad chain parameter id [ALLOW_TVM_STAKE]"); - } - if (value != 1 && value != 0) { - throw new ContractValidateException( - "This value[ALLOW_TVM_STAKE] is only allowed to be 1 or 0"); - } - break; - } +// case ALLOW_TVM_STAKE: { +// if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_1)) { +// throw new ContractValidateException( +// "Bad chain parameter id [ALLOW_TVM_STAKE]"); +// } +// if (value != 1 && value != 0) { +// throw new ContractValidateException( +// "This value[ALLOW_TVM_STAKE] is only allowed to be 1 or 0"); +// } +// break; +// } case ALLOW_TVM_ASSET_ISSUE: { if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_1)) { throw new ContractValidateException( @@ -446,7 +446,7 @@ public enum ProposalType { // current value, value range ALLOW_PBFT(40),// 1,40 ALLOW_TVM_ISTANBUL(41),//1, {0,1} ALLOW_TVM_ASSET_ISSUE(42), // 0, 1 - ALLOW_TVM_STAKE(43), // 0, 1 + // ALLOW_TVM_STAKE(43), // 0, 1 ALLOW_MARKET_TRANSACTION(44), // {0, 1} MARKET_SELL_FEE(45), // 0 [0,10_000_000_000] MARKET_CANCEL_FEE(46); // 0 [0,10_000_000_000] diff --git a/framework/src/main/java/org/tron/core/consensus/ProposalService.java b/framework/src/main/java/org/tron/core/consensus/ProposalService.java index d5e11ff3f23..95ae3476d52 100644 --- a/framework/src/main/java/org/tron/core/consensus/ProposalService.java +++ b/framework/src/main/java/org/tron/core/consensus/ProposalService.java @@ -206,10 +206,10 @@ public static boolean process(Manager manager, ProposalCapsule proposalCapsule) manager.getDynamicPropertiesStore().saveAllowShieldedTRC20Transaction(entry.getValue()); break; } - case ALLOW_TVM_STAKE: { - manager.getDynamicPropertiesStore().saveAllowTvmStake(entry.getValue()); - break; - } +// case ALLOW_TVM_STAKE: { +// manager.getDynamicPropertiesStore().saveAllowTvmStake(entry.getValue()); +// break; +// } case ALLOW_TVM_ASSET_ISSUE: { manager.getDynamicPropertiesStore().saveAllowTvmAssetIssue(entry.getValue()); break; From 39e6c03fee6b29a4a21d5109b65ed3591f46a952 Mon Sep 17 00:00:00 2001 From: xiangdepeng Date: Thu, 22 Oct 2020 17:38:12 +0800 Subject: [PATCH 37/60] fix sonar --- .../java/org/tron/core/consensus/ProposalService.java | 8 ++++---- framework/src/main/java/org/tron/core/db/Manager.java | 3 ++- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/framework/src/main/java/org/tron/core/consensus/ProposalService.java b/framework/src/main/java/org/tron/core/consensus/ProposalService.java index 95ae3476d52..765422156d4 100644 --- a/framework/src/main/java/org/tron/core/consensus/ProposalService.java +++ b/framework/src/main/java/org/tron/core/consensus/ProposalService.java @@ -206,10 +206,10 @@ public static boolean process(Manager manager, ProposalCapsule proposalCapsule) manager.getDynamicPropertiesStore().saveAllowShieldedTRC20Transaction(entry.getValue()); break; } -// case ALLOW_TVM_STAKE: { -// manager.getDynamicPropertiesStore().saveAllowTvmStake(entry.getValue()); -// break; -// } + //case ALLOW_TVM_STAKE: { + // manager.getDynamicPropertiesStore().saveAllowTvmStake(entry.getValue()); + // break; + //} case ALLOW_TVM_ASSET_ISSUE: { manager.getDynamicPropertiesStore().saveAllowTvmAssetIssue(entry.getValue()); break; diff --git a/framework/src/main/java/org/tron/core/db/Manager.java b/framework/src/main/java/org/tron/core/db/Manager.java index d62373e22eb..fbf4a4e556c 100644 --- a/framework/src/main/java/org/tron/core/db/Manager.java +++ b/framework/src/main/java/org/tron/core/db/Manager.java @@ -902,7 +902,8 @@ public synchronized void pushBlock(final BlockCapsule block) try { newBlock = this.khaosDb.push(block); } catch (UnLinkedBlockException e) { - logger.error("latestBlockHeaderHash:{}, latestBlockHeaderNumber:{}, latestSolidifiedBlockNum:{}", + logger.error( + "latestBlockHeaderHash:{}, latestBlockHeaderNumber:{}, latestSolidifiedBlockNum:{}", getDynamicPropertiesStore().getLatestBlockHeaderHash(), getDynamicPropertiesStore().getLatestBlockHeaderNumber(), getDynamicPropertiesStore().getLatestSolidifiedBlockNum()); From 7f4929bec66fe47b3ea5a3fad2e448244398a28b Mon Sep 17 00:00:00 2001 From: xiangdepeng Date: Sat, 24 Oct 2020 14:49:57 +0800 Subject: [PATCH 38/60] delete ALLOW_TVM_ASSET_ISSUE proposal --- .../org/tron/core/utils/ProposalUtil.java | 27 ++++++++++--------- .../tron/core/consensus/ProposalService.java | 8 +++--- 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java b/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java index e1a299989a3..5c9c7e92879 100644 --- a/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java +++ b/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java @@ -15,7 +15,8 @@ public class ProposalUtil { private static final String PRE_VALUE_NOT_ONE_ERROR = "This value["; private static final String VALUE_NOT_ONE_ERROR = "] is only allowed to be 1"; private static final long MAX_SUPPLY = 100_000_000_000L; - private static final String MAX_SUPPLY_ERROR = "Bad chain parameter value, valid range is [0, 100_000_000_000L]"; + private static final String MAX_SUPPLY_ERROR + = "Bad chain parameter value, valid range is [0, 100_000_000_000L]"; public static void validator(DynamicPropertiesStore dynamicPropertiesStore, ForkController forkController, @@ -350,17 +351,17 @@ public static void validator(DynamicPropertiesStore dynamicPropertiesStore, // } // break; // } - case ALLOW_TVM_ASSET_ISSUE: { - if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_1)) { - throw new ContractValidateException( - "Bad chain parameter id [ALLOW_TVM_ASSET_ISSUE]"); - } - if (value != 1 && value != 0) { - throw new ContractValidateException( - "This value[ALLOW_TVM_ASSET_ISSUE] is only allowed to be 1 or 0"); - } - break; - } + // case ALLOW_TVM_ASSET_ISSUE: { + // if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_1)) { + // throw new ContractValidateException( + // "Bad chain parameter id [ALLOW_TVM_ASSET_ISSUE]"); + // } + // if (value != 1 && value != 0) { + // throw new ContractValidateException( + // "This value[ALLOW_TVM_ASSET_ISSUE] is only allowed to be 1 or 0"); + // } + // break; + //} case ALLOW_MARKET_TRANSACTION: { if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_1)) { throw new ContractValidateException( @@ -445,7 +446,7 @@ public enum ProposalType { // current value, value range ALLOW_SHIELDED_TRC20_TRANSACTION(39), // 1, 39 ALLOW_PBFT(40),// 1,40 ALLOW_TVM_ISTANBUL(41),//1, {0,1} - ALLOW_TVM_ASSET_ISSUE(42), // 0, 1 + //ALLOW_TVM_ASSET_ISSUE(42), // 0, 1 // ALLOW_TVM_STAKE(43), // 0, 1 ALLOW_MARKET_TRANSACTION(44), // {0, 1} MARKET_SELL_FEE(45), // 0 [0,10_000_000_000] diff --git a/framework/src/main/java/org/tron/core/consensus/ProposalService.java b/framework/src/main/java/org/tron/core/consensus/ProposalService.java index 765422156d4..f8952c5f8eb 100644 --- a/framework/src/main/java/org/tron/core/consensus/ProposalService.java +++ b/framework/src/main/java/org/tron/core/consensus/ProposalService.java @@ -210,10 +210,10 @@ public static boolean process(Manager manager, ProposalCapsule proposalCapsule) // manager.getDynamicPropertiesStore().saveAllowTvmStake(entry.getValue()); // break; //} - case ALLOW_TVM_ASSET_ISSUE: { - manager.getDynamicPropertiesStore().saveAllowTvmAssetIssue(entry.getValue()); - break; - } + //case ALLOW_TVM_ASSET_ISSUE: { + // manager.getDynamicPropertiesStore().saveAllowTvmAssetIssue(entry.getValue()); + // break; + //} case ALLOW_MARKET_TRANSACTION: { if (manager.getDynamicPropertiesStore().getAllowMarketTransaction() == 0) { manager.getDynamicPropertiesStore().saveAllowMarketTransaction(entry.getValue()); From 614de7462b8789ef140d353e3e91044b18ad4ccc Mon Sep 17 00:00:00 2001 From: renchenchang Date: Mon, 26 Oct 2020 17:36:51 +0800 Subject: [PATCH 39/60] fix name parse error --- .../java/org/tron/core/services/http/JsonFormat.java | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/framework/src/main/java/org/tron/core/services/http/JsonFormat.java b/framework/src/main/java/org/tron/core/services/http/JsonFormat.java index 0a1bad1c4b3..cdb69d79ff0 100644 --- a/framework/src/main/java/org/tron/core/services/http/JsonFormat.java +++ b/framework/src/main/java/org/tron/core/services/http/JsonFormat.java @@ -29,8 +29,7 @@ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -import com.alibaba.fastjson.parser.DefaultJSONParser; -import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.JSON; import com.google.protobuf.ByteString; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.EnumDescriptor; @@ -761,11 +760,7 @@ static String escapeBytesSelfType(ByteString input, final String fliedName) { String result = new String(input.toByteArray()); result = result.replaceAll("\"", "\\\\\""); try { - DefaultJSONParser parser = new DefaultJSONParser(result, ParserConfig.getGlobalInstance(), - 0); - Object value = parser.parse(); - parser.handleResovleTask(value); - parser.close(); + JSON.parseObject("{\"key\":\"" + result + "\"}"); return result; } catch (Exception e) { return ByteArray.toHexString(input.toByteArray()); From 5520276d182c37145e2298e1722201838654253c Mon Sep 17 00:00:00 2001 From: taihaofu Date: Tue, 27 Oct 2020 17:24:52 +0800 Subject: [PATCH 40/60] fix dataword --- actuator/src/main/java/org/tron/core/vm/program/Program.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actuator/src/main/java/org/tron/core/vm/program/Program.java b/actuator/src/main/java/org/tron/core/vm/program/Program.java index bd2f5b93833..ae8e472d0bf 100644 --- a/actuator/src/main/java/org/tron/core/vm/program/Program.java +++ b/actuator/src/main/java/org/tron/core/vm/program/Program.java @@ -1178,7 +1178,7 @@ public DataWord getBlockHash(int index) { BlockCapsule blockCapsule = contractState.getBlockByNum(index); if (Objects.nonNull(blockCapsule)) { - return new DataWord(blockCapsule.getBlockId().getBytes()); + return new DataWord(blockCapsule.getBlockId().getBytes()).clone(); } else { return DataWord.ZERO.clone(); } From 8674a396c554ea314e63d285a603bebb92bc3ce7 Mon Sep 17 00:00:00 2001 From: kiven Date: Wed, 28 Oct 2020 20:54:26 +0800 Subject: [PATCH 41/60] fix the node start error (#3473) * fix the node start error * fix the code error --- .../main/java/org/tron/keystore/Wallet.java | 16 +++--- .../java/org/tron/keystore/WalletFile.java | 57 +++++++++---------- 2 files changed, 36 insertions(+), 37 deletions(-) diff --git a/framework/src/main/java/org/tron/keystore/Wallet.java b/framework/src/main/java/org/tron/keystore/Wallet.java index dc76441537f..5c7618ce943 100644 --- a/framework/src/main/java/org/tron/keystore/Wallet.java +++ b/framework/src/main/java/org/tron/keystore/Wallet.java @@ -97,12 +97,12 @@ private static WalletFile createWalletFile( WalletFile.Crypto crypto = new WalletFile.Crypto(); crypto.setCipher(CIPHER); - crypto.setCipherText(ByteArray.toHexString(cipherText)); + crypto.setCiphertext(ByteArray.toHexString(cipherText)); walletFile.setCrypto(crypto); WalletFile.CipherParams cipherParams = new WalletFile.CipherParams(); cipherParams.setIv(ByteArray.toHexString(iv)); - crypto.setCipherParams(cipherParams); + crypto.setCipherparams(cipherParams); crypto.setKdf(SCRYPT); WalletFile.ScryptKdfParams kdfParams = new WalletFile.ScryptKdfParams(); @@ -111,7 +111,7 @@ private static WalletFile createWalletFile( kdfParams.setP(p); kdfParams.setR(R); kdfParams.setSalt(ByteArray.toHexString(salt)); - crypto.setKdfParams(kdfParams); + crypto.setKdfparams(kdfParams); crypto.setMac(ByteArray.toHexString(mac)); walletFile.setCrypto(crypto); @@ -175,15 +175,15 @@ public static SignInterface decrypt(String password, WalletFile walletFile) WalletFile.Crypto crypto = walletFile.getCrypto(); byte[] mac = ByteArray.fromHexString(crypto.getMac()); - byte[] iv = ByteArray.fromHexString(crypto.getCipherParams().getIv()); - byte[] cipherText = ByteArray.fromHexString(crypto.getCipherText()); + byte[] iv = ByteArray.fromHexString(crypto.getCipherparams().getIv()); + byte[] cipherText = ByteArray.fromHexString(crypto.getCiphertext()); byte[] derivedKey; - WalletFile.KdfParams kdfParams = crypto.getKdfParams(); + WalletFile.KdfParams kdfParams = crypto.getKdfparams(); if (kdfParams instanceof WalletFile.ScryptKdfParams) { WalletFile.ScryptKdfParams scryptKdfParams = - (WalletFile.ScryptKdfParams) crypto.getKdfParams(); + (WalletFile.ScryptKdfParams) crypto.getKdfparams(); int dklen = scryptKdfParams.getDklen(); int n = scryptKdfParams.getN(); int p = scryptKdfParams.getP(); @@ -192,7 +192,7 @@ public static SignInterface decrypt(String password, WalletFile walletFile) derivedKey = generateDerivedScryptKey(password.getBytes(UTF_8), salt, n, r, p, dklen); } else if (kdfParams instanceof WalletFile.Aes128CtrKdfParams) { WalletFile.Aes128CtrKdfParams aes128CtrKdfParams = - (WalletFile.Aes128CtrKdfParams) crypto.getKdfParams(); + (WalletFile.Aes128CtrKdfParams) crypto.getKdfparams(); int c = aes128CtrKdfParams.getC(); String prf = aes128CtrKdfParams.getPrf(); byte[] salt = ByteArray.fromHexString(aes128CtrKdfParams.getSalt()); diff --git a/framework/src/main/java/org/tron/keystore/WalletFile.java b/framework/src/main/java/org/tron/keystore/WalletFile.java index a7fb348fd45..1f5135fefd3 100644 --- a/framework/src/main/java/org/tron/keystore/WalletFile.java +++ b/framework/src/main/java/org/tron/keystore/WalletFile.java @@ -10,7 +10,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; -import java.util.Objects; /** * Ethereum wallet file. @@ -68,7 +67,7 @@ public boolean equals(Object o) { if (this == o) { return true; } - if (Objects.isNull(o)) { + if (o == null) { return false; } if (o.getClass() != this.getClass()) { @@ -114,11 +113,11 @@ interface KdfParams { public static class Crypto { private String cipher; - private String cipherText; - private CipherParams cipherParams; + private String ciphertext; + private CipherParams cipherparams; private String kdf; - private KdfParams kdfParams; + private KdfParams kdfparams; private String mac; @@ -133,20 +132,20 @@ public void setCipher(String cipher) { this.cipher = cipher; } - public String getCipherText() { - return cipherText; + public String getCiphertext() { + return ciphertext; } - public void setCipherText(String cipherText) { - this.cipherText = cipherText; + public void setCiphertext(String ciphertext) { + this.ciphertext = ciphertext; } - public CipherParams getCipherParams() { - return cipherParams; + public CipherParams getCipherparams() { + return cipherparams; } - public void setCipherParams(CipherParams cipherParams) { - this.cipherParams = cipherParams; + public void setCipherparams(CipherParams cipherparams) { + this.cipherparams = cipherparams; } public String getKdf() { @@ -157,8 +156,8 @@ public void setKdf(String kdf) { this.kdf = kdf; } - public KdfParams getKdfParams() { - return kdfParams; + public KdfParams getKdfparams() { + return kdfparams; } @JsonTypeInfo( @@ -173,8 +172,8 @@ public KdfParams getKdfParams() { // @JsonDeserialize(using = KdfParamsDeserialiser.class) // Also add the following to the ObjectMapperFactory // objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true); - public void setKdfParams(KdfParams kdfParams) { - this.kdfParams = kdfParams; + public void setKdfparams(KdfParams kdfparams) { + this.kdfparams = kdfparams; } public String getMac() { @@ -204,14 +203,14 @@ public boolean equals(Object o) { : that.getCipher() != null) { return false; } - if (getCipherText() != null - ? !getCipherText().equals(that.getCipherText()) - : that.getCipherText() != null) { + if (getCiphertext() != null + ? !getCiphertext().equals(that.getCiphertext()) + : that.getCiphertext() != null) { return false; } - if (getCipherParams() != null - ? !getCipherParams().equals(that.getCipherParams()) - : that.getCipherParams() != null) { + if (getCipherparams() != null + ? !getCipherparams().equals(that.getCipherparams()) + : that.getCipherparams() != null) { return false; } if (getKdf() != null @@ -219,9 +218,9 @@ public boolean equals(Object o) { : that.getKdf() != null) { return false; } - if (getKdfParams() != null - ? !getKdfParams().equals(that.getKdfParams()) - : that.getKdfParams() != null) { + if (getKdfparams() != null + ? !getKdfparams().equals(that.getKdfparams()) + : that.getKdfparams() != null) { return false; } return getMac() != null @@ -231,10 +230,10 @@ public boolean equals(Object o) { @Override public int hashCode() { int result = getCipher() != null ? getCipher().hashCode() : 0; - result = 31 * result + (getCipherText() != null ? getCipherText().hashCode() : 0); - result = 31 * result + (getCipherParams() != null ? getCipherParams().hashCode() : 0); + result = 31 * result + (getCiphertext() != null ? getCiphertext().hashCode() : 0); + result = 31 * result + (getCipherparams() != null ? getCipherparams().hashCode() : 0); result = 31 * result + (getKdf() != null ? getKdf().hashCode() : 0); - result = 31 * result + (getKdfParams() != null ? getKdfParams().hashCode() : 0); + result = 31 * result + (getKdfparams() != null ? getKdfparams().hashCode() : 0); result = 31 * result + (getMac() != null ? getMac().hashCode() : 0); return result; } From 6d831bafc88e23d813223907b2a118c254e1f9d3 Mon Sep 17 00:00:00 2001 From: taihaofu Date: Wed, 4 Nov 2020 15:43:41 +0800 Subject: [PATCH 42/60] refine code --- .../main/java/org/tron/core/vm/OpCode.java | 28 +-- .../src/main/java/org/tron/core/vm/VM.java | 220 +++++++++--------- 2 files changed, 129 insertions(+), 119 deletions(-) diff --git a/actuator/src/main/java/org/tron/core/vm/OpCode.java b/actuator/src/main/java/org/tron/core/vm/OpCode.java index 08166420ea1..5b8cc279d00 100644 --- a/actuator/src/main/java/org/tron/core/vm/OpCode.java +++ b/actuator/src/main/java/org/tron/core/vm/OpCode.java @@ -585,20 +585,20 @@ public enum OpCode { CALLTOKENID(0xd3, 0, 1, OpCode.Tier.BaseTier), ISCONTRACT(0xd4, 1, 1, OpCode.Tier.ExtTier), - - STAKE(0xd5, 2, 1, OpCode.Tier.ExtTier), - - UNSTAKE(0xd6, 0, 1, OpCode.Tier.ExtTier), - - WITHDRAWREWARD(0xd7, 1, 1, OpCode.Tier.ExtTier), - - REWARDBALANCE(0xd8, 1, 1, OpCode.Tier.ExtTier), - - ISSRCANDIDATE(0xd9, 1, 1, OpCode.Tier.ExtTier), - - TOKENISSUE(0xda, 1, 1, Tier.HighTier), - - UPDATEASSET(0xdb, 1, 1, OpCode.Tier.HighTier), +// +// STAKE(0xd5, 2, 1, OpCode.Tier.ExtTier), +// +// UNSTAKE(0xd6, 0, 1, OpCode.Tier.ExtTier), +// +// WITHDRAWREWARD(0xd7, 1, 1, OpCode.Tier.ExtTier), +// +// REWARDBALANCE(0xd8, 1, 1, OpCode.Tier.ExtTier), +// +// ISSRCANDIDATE(0xd9, 1, 1, OpCode.Tier.ExtTier), +// +// TOKENISSUE(0xda, 1, 1, Tier.HighTier), +// +// UPDATEASSET(0xdb, 1, 1, OpCode.Tier.HighTier), /** * (0xf0) Create a new account with associated code */ diff --git a/actuator/src/main/java/org/tron/core/vm/VM.java b/actuator/src/main/java/org/tron/core/vm/VM.java index 506cad0e375..023f36bf4cf 100644 --- a/actuator/src/main/java/org/tron/core/vm/VM.java +++ b/actuator/src/main/java/org/tron/core/vm/VM.java @@ -34,13 +34,16 @@ public class VM { // 3MB private static final BigInteger MEM_LIMIT = BigInteger.valueOf(3L * 1024 * 1024); private final VMConfig config; +// private boolean passIstanbul; public VM() { config = VMConfig.getInstance(); +// passIstanbul = VMConfig.allowTvmIstanbul(); } public VM(VMConfig config) { this.config = config; +// passIstanbul = VMConfig.allowTvmIstanbul(); } /** @@ -92,38 +95,45 @@ public void step(Program program) { try { OpCode op = OpCode.code(program.getCurrentOp()); - if (op == null) { + if (op == null + || (!VMConfig.allowTvmTransferTrc10() + && (op == CALLTOKEN || op == TOKENBALANCE || op == CALLTOKENVALUE + || op == CALLTOKENID)) + || (!VMConfig.allowTvmConstantinople() + && (op == SHL || op == SHR || op == SAR || op == CREATE2 || op == EXTCODEHASH)) + || (!VMConfig.allowTvmSolidity059() && op == ISCONTRACT) + || (!VMConfig.allowTvmIstanbul() && (op == SELFBALANCE || op == CHAINID)) + ) { throw Program.Exception.invalidOpCode(program.getCurrentOp()); } // hard fork for 3.2 - if (!VMConfig.allowTvmTransferTrc10() - && (op == CALLTOKEN || op == TOKENBALANCE || op == CALLTOKENVALUE || op == CALLTOKENID)) { - throw Program.Exception.invalidOpCode(program.getCurrentOp()); - } - - if (!VMConfig.allowTvmConstantinople() - && (op == SHL || op == SHR || op == SAR || op == CREATE2 || op == EXTCODEHASH)) { - throw Program.Exception.invalidOpCode(program.getCurrentOp()); - } - - if (!VMConfig.allowTvmSolidity059() && op == ISCONTRACT) { - throw Program.Exception.invalidOpCode(program.getCurrentOp()); - } - - if (!VMConfig.allowTvmIstanbul() && (op == SELFBALANCE || op == CHAINID)) { - throw Program.Exception.invalidOpCode(program.getCurrentOp()); - } - - if (!VMConfig.allowTvmStake() - && (op == ISSRCANDIDATE || op == REWARDBALANCE || op == STAKE || op == UNSTAKE - || op == WITHDRAWREWARD)) { - throw Program.Exception.invalidOpCode(program.getCurrentOp()); - } - - if(!VMConfig.allowTvmAssetIssue() && (op == TOKENISSUE || op == UPDATEASSET)) { - throw Program.Exception.invalidOpCode(program.getCurrentOp()); - } +// if (!VMConfig.allowTvmTransferTrc10() +// && (op == CALLTOKEN || op == TOKENBALANCE || op == CALLTOKENVALUE || op == CALLTOKENID)) { +// throw Program.Exception.invalidOpCode(program.getCurrentOp()); +// } +// +// if (!VMConfig.allowTvmConstantinople() +// && (op == SHL || op == SHR || op == SAR || op == CREATE2 || op == EXTCODEHASH)) { +// throw Program.Exception.invalidOpCode(program.getCurrentOp()); +// } +// +// if (!VMConfig.allowTvmSolidity059() && op == ISCONTRACT) { +// throw Program.Exception.invalidOpCode(program.getCurrentOp()); +// } + +// if (!VMConfig.allowTvmIstanbul() && (op == SELFBALANCE || op == CHAINID)) { +// throw Program.Exception.invalidOpCode(program.getCurrentOp()); +// } +// if (!VMConfig.allowTvmStake() +// && (op == ISSRCANDIDATE || op == REWARDBALANCE || op == STAKE || op == UNSTAKE +// || op == WITHDRAWREWARD)) { +// throw Program.Exception.invalidOpCode(program.getCurrentOp()); +// } +// +// if(!VMConfig.allowTvmAssetIssue() && (op == TOKENISSUE || op == UPDATEASSET)) { +// throw Program.Exception.invalidOpCode(program.getCurrentOp()); +// } program.setLastOp(op.val()); program.verifyStackSize(op.require()); @@ -173,9 +183,9 @@ public void step(Program program) { break; case TOKENBALANCE: case BALANCE: - case REWARDBALANCE: +// case REWARDBALANCE: case ISCONTRACT: - case ISSRCANDIDATE: +// case ISSRCANDIDATE: energyCost = energyCosts.getBALANCE(); break; @@ -317,19 +327,19 @@ && isDeadAccount(program, callAddressWord) energyCost = (long) energyCosts.getEXP_ENERGY() + energyCosts.getEXP_BYTE_ENERGY() * bytesOccupied; break; - case STAKE: - case UNSTAKE: - energyCost = energyCosts.getStakeAndUnstake(); - break; - case WITHDRAWREWARD: - energyCost = energyCosts.getWithdrawReward(); - break; - case TOKENISSUE: - energyCost = energyCosts.getTokenIssue(); - break; - case UPDATEASSET: - energyCost = energyCosts.getUpdateAsset(); - break; +// case STAKE: +// case UNSTAKE: +// energyCost = energyCosts.getStakeAndUnstake(); +// break; +// case WITHDRAWREWARD: +// energyCost = energyCosts.getWithdrawReward(); +// break; +// case TOKENISSUE: +// energyCost = energyCosts.getTokenIssue(); +// break; +// case UPDATEASSET: +// energyCost = energyCosts.getUpdateAsset(); +// break; default: break; } @@ -763,20 +773,20 @@ && isDeadAccount(program, callAddressWord) program.step(); } break; - case REWARDBALANCE: { - DataWord address = program.stackPop(); - DataWord rewardBalance = program.getRewardBalance(address); - - if (logger.isDebugEnabled()) { - hint = ADDRESS_LOG - + Hex.toHexString(address.getLast20Bytes()) - + " reward balance: " + rewardBalance.toString(); - } - - program.stackPush(rewardBalance); - program.step(); - } - break; +// case REWARDBALANCE: { +// DataWord address = program.stackPop(); +// DataWord rewardBalance = program.getRewardBalance(address); +// +// if (logger.isDebugEnabled()) { +// hint = ADDRESS_LOG +// + Hex.toHexString(address.getLast20Bytes()) +// + " reward balance: " + rewardBalance.toString(); +// } +// +// program.stackPush(rewardBalance); +// program.step(); +// } +// break; case ISCONTRACT: { DataWord address = program.stackPop(); DataWord isContract = program.isContract(address); @@ -785,14 +795,14 @@ && isDeadAccount(program, callAddressWord) program.step(); } break; - case ISSRCANDIDATE: { - DataWord address = program.stackPop(); - DataWord isSRCandidate = program.isSRCandidate(address); - - program.stackPush(isSRCandidate); - program.step(); - } - break; +// case ISSRCANDIDATE: { +// DataWord address = program.stackPop(); +// DataWord isSRCandidate = program.isSRCandidate(address); +// +// program.stackPush(isSRCandidate); +// program.step(); +// } +// break; case ORIGIN: { DataWord originAddress = program.getOriginAddress(); @@ -1452,46 +1462,46 @@ && isDeadAccount(program, callAddressWord) program.step(); break; } - case STAKE: { - DataWord srAddress = program.stackPop(); - DataWord stakeAmount = program.stackPop(); - boolean result = program.stake(srAddress, stakeAmount); - program.stackPush(new DataWord(result ? 1 : 0)); - - program.step(); - } - break; - case UNSTAKE: { - boolean result = program.unstake(); - program.stackPush(new DataWord(result ? 1 : 0)); - - program.step(); - } - break; - case WITHDRAWREWARD: { - program.withdrawReward(); - program.step(); - } - break; - case TOKENISSUE: { - DataWord name = program.stackPop(); - DataWord abbr = program.stackPop(); - DataWord totalSupply = program.stackPop(); - DataWord precision = program.stackPop(); - - program.tokenIssue(name, abbr, totalSupply, precision); - program.step(); - break; - } - case UPDATEASSET: { - program.stackPop(); - DataWord urlDataOffs = program.stackPop(); - DataWord descriptionDataOffs = program.stackPop(); - - program.updateAsset(urlDataOffs, descriptionDataOffs); - program.step(); - break; - } +// case STAKE: { +// DataWord srAddress = program.stackPop(); +// DataWord stakeAmount = program.stackPop(); +// boolean result = program.stake(srAddress, stakeAmount); +// program.stackPush(new DataWord(result ? 1 : 0)); +// +// program.step(); +// } +// break; +// case UNSTAKE: { +// boolean result = program.unstake(); +// program.stackPush(new DataWord(result ? 1 : 0)); +// +// program.step(); +// } +// break; +// case WITHDRAWREWARD: { +// program.withdrawReward(); +// program.step(); +// } +// break; +// case TOKENISSUE: { +// DataWord name = program.stackPop(); +// DataWord abbr = program.stackPop(); +// DataWord totalSupply = program.stackPop(); +// DataWord precision = program.stackPop(); +// +// program.tokenIssue(name, abbr, totalSupply, precision); +// program.step(); +// break; +// } +// case UPDATEASSET: { +// program.stackPop(); +// DataWord urlDataOffs = program.stackPop(); +// DataWord descriptionDataOffs = program.stackPop(); +// +// program.updateAsset(urlDataOffs, descriptionDataOffs); +// program.step(); +// break; +// } case RETURN: case REVERT: { DataWord offset = program.stackPop(); From 1106a1e705a958553b50a9525cf7f0449dfb4d89 Mon Sep 17 00:00:00 2001 From: taihaofu Date: Wed, 4 Nov 2020 16:00:52 +0800 Subject: [PATCH 43/60] optimize tvm release4.1 --- actuator/src/main/java/org/tron/core/vm/VM.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/actuator/src/main/java/org/tron/core/vm/VM.java b/actuator/src/main/java/org/tron/core/vm/VM.java index 023f36bf4cf..6e1660743cf 100644 --- a/actuator/src/main/java/org/tron/core/vm/VM.java +++ b/actuator/src/main/java/org/tron/core/vm/VM.java @@ -34,16 +34,13 @@ public class VM { // 3MB private static final BigInteger MEM_LIMIT = BigInteger.valueOf(3L * 1024 * 1024); private final VMConfig config; -// private boolean passIstanbul; public VM() { config = VMConfig.getInstance(); -// passIstanbul = VMConfig.allowTvmIstanbul(); } public VM(VMConfig config) { this.config = config; -// passIstanbul = VMConfig.allowTvmIstanbul(); } /** From 8173f8e9ee12745d5ae040520b6a65895f854860 Mon Sep 17 00:00:00 2001 From: xiangdepeng Date: Wed, 4 Nov 2020 18:18:54 +0800 Subject: [PATCH 44/60] remove unit test for proposal Stake and AssetIssue --- .../common/runtime/vm/IsSRCandidateTest.java | 526 ++--- .../common/runtime/vm/RewardBalanceTest.java | 530 ++--- .../org/tron/common/runtime/vm/StakeTest.java | 372 ++-- .../tron/common/runtime/vm/SuicideTest.java | 716 +++--- .../org/tron/common/runtime/vm/Trc10Test.java | 1318 ++++++------ .../tron/common/runtime/vm/UnStakeTest.java | 258 +-- .../common/runtime/vm/WithdrawRewardTest.java | 1912 ++++++++--------- 7 files changed, 2816 insertions(+), 2816 deletions(-) diff --git a/framework/src/test/java/org/tron/common/runtime/vm/IsSRCandidateTest.java b/framework/src/test/java/org/tron/common/runtime/vm/IsSRCandidateTest.java index 55098995e6f..d03699ee95c 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/IsSRCandidateTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/IsSRCandidateTest.java @@ -1,263 +1,263 @@ -package org.tron.common.runtime.vm; - -import java.util.Collections; -import lombok.extern.slf4j.Slf4j; -import org.junit.Test; -import org.spongycastle.util.encoders.Hex; -import org.testng.Assert; -import org.tron.common.runtime.TVMTestResult; -import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.WalletUtil; -import org.tron.core.exception.ContractExeException; -import org.tron.core.exception.ContractValidateException; -import org.tron.core.exception.ReceiptCheckErrException; -import org.tron.core.exception.VMIllegalException; -import org.tron.core.vm.config.ConfigLoader; -import org.tron.core.vm.config.VMConfig; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.utils.AbiUtil; - -@Slf4j -public class IsSRCandidateTest extends VMTestBase { - - /* - pragma solidity ^0.5.0; - - contract ContractB{ - address others; - } - - contract TestIsSRCandidate{ - address user; - - ContractB contractB = new ContractB(); - - constructor() public { - user = msg.sender; - } - - function isSRCandidateTest(address addr) public returns (bool) { - return address(addr).isSRCandidate; - } - - function nullAddressTest() public returns (bool) { - return address(0x0).isSRCandidate; - } - - function localContractAddrTest() public returns (bool) { - address payable localContract = address(uint160(address(this))); - return localContract.isSRCandidate; - - return address(this).isSRCandidate; - } - - function otherContractAddrTest() public returns (bool) { - return address(contractB).isSRCandidate; - } - - function nonpayableAddrTest(address addr) public returns (bool) { - return addr.isSRCandidate; - } - - function payableAddrTest(address payable addr) public returns (bool) { - return addr.isSRCandidate; - } - } - */ - - @Test - public void testIsSRCandidate() - throws ContractExeException, ReceiptCheckErrException, VMIllegalException, - ContractValidateException { - ConfigLoader.disable = true; - VMConfig.initAllowTvmTransferTrc10(1); - VMConfig.initAllowTvmConstantinople(1); - VMConfig.initAllowTvmSolidity059(1); - VMConfig.initAllowTvmStake(1); - String contractName = "TestIsSRCandidate"; - byte[] address = Hex.decode(OWNER_ADDRESS); - String abi = "[{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\"," - + "\"type\":\"constructor\"},{\"constant\":false," - + "\"inputs\":[{\"internalType\":\"address\",\"name\":\"addr\"," - + "\"type\":\"address\"}],\"name\":\"isSRCandidateTest\"," - + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," - + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," - + "{\"constant\":false,\"inputs\":[],\"name\":\"localContractAddrTest\"," - + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," - + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," - + "{\"constant\":false,\"inputs\":[{\"internalType\":\"address\"," - + "\"name\":\"addr\",\"type\":\"address\"}],\"name\":\"nonpayableAddrTest\"," - + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," - + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," - + "{\"constant\":false,\"inputs\":[],\"name\":\"nullAddressTest\"," - + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," - + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," - + "{\"constant\":false,\"inputs\":[],\"name\":\"otherContractAddrTest\"," - + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," - + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," - + "{\"constant\":false,\"inputs\":[{\"internalType\":\"address payable\"," - + "\"name\":\"addr\",\"type\":\"address\"}],\"name\":\"payableAddrTest\"," - + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," - + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"; - - String factoryCode = "60806040526040516100109061008b565b6" - + "04051809103906000f08015801561002c573d6000803e3d6" - + "000fd5b50600180546001600160a01b0319166001600160a" - + "01b039290921691909117905534801561005957600080fd5" - + "b50d3801561006657600080fd5b50d280156100735760008" - + "0fd5b50600080546001600160a01b0319163317905561009" - + "7565b6072806101c283390190565b61011c806100a660003" - + "96000f3fe6080604052348015600f57600080fd5b50d3801" - + "5601b57600080fd5b50d28015602757600080fd5b5060043" - + "61060725760003560e01c80632e48f1ac14607757806356b" - + "42994146077578063627bfa45146077578063af4a1105146" - + "0ae578063cb2d51cf1460b4578063d30a28ee1460ba575b6" - + "00080fd5b609a60048036036020811015608b57600080fd5" - + "b50356001600160a01b031660c0565b60408051911515825" - + "2519081900360200190f35b609a60cd565b609a60d3565b6" - + "09a60d8565b6001600160a01b0316d990565b6000d990565" - + "b30d990565b6001546001600160a01b0316d99056fea2647" - + "4726f6e5820509553fa5821ca76ddf8a0d074cd74dcb1f74" - + "e068ca148b983f1b0bea447b99f64736f6c634300050d003" - + "16080604052348015600f57600080fd5b50d38015601b576" - + "00080fd5b50d28015602757600080fd5b50603d806035600" - + "0396000f3fe6080604052600080fdfea26474726f6e58209" - + "afab2d7a84ca331e2eb33393a62310b1a53e77c37a287407" - + "53ae0a3a99980ba64736f6c634300050d0031"; - long value = 0; - long fee = 100000000; - long consumeUserResourcePercent = 0; - - // deploy contract - Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, - null); - byte[] factoryAddress = WalletUtil.generateContractAddress(trx); - String factoryAddressStr = StringUtil.encode58Check(factoryAddress); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); - Assert.assertNull(runtime.getRuntimeError()); - - // Trigger contract method: isSRCandidateTest(address) - String methodByAddr = "isSRCandidateTest(address)"; - String nonexistentAccount = "27k66nycZATHzBasFT9782nTsYWqVtxdtAc"; - String hexInput = AbiUtil.parseMethod(methodByAddr, - Collections.singletonList(nonexistentAccount)); - TVMTestResult result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - byte[] returnValue = result.getRuntime().getResult().getHReturn(); - // check deployed contract - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // trigger deployed contract - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - // check deployed contract - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // trigger deployed contract - String witnessAccount = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(witnessAccount)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - // check deployed contract - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000001"); - - // Trigger contract method: nullAddressTest(address) - methodByAddr = "nullAddressTest()"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - // check deployed contract - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // Trigger contract method: localContractAddrTest() - methodByAddr = "localContractAddrTest()"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - // check deployed contract - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // Trigger contract method: otherContractAddrTest() - methodByAddr = "otherContractAddrTest()"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - // check deployed contract - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // Trigger contract method: nonpayableAddrTest(address) - methodByAddr = "nonpayableAddrTest(address)"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(witnessAccount)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - // check deployed contract - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000001"); - - // Trigger contract method: nonpayableAddrTest(address) - methodByAddr = "nonpayableAddrTest(address)"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(nonexistentAccount)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - // check deployed contract - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // Trigger contract method: payableAddrTest(address) - methodByAddr = "payableAddrTest(address)"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(nonexistentAccount)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - // check deployed contract - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - ConfigLoader.disable = false; - } -} - - +//package org.tron.common.runtime.vm; +// +//import java.util.Collections; +//import lombok.extern.slf4j.Slf4j; +//import org.junit.Test; +//import org.spongycastle.util.encoders.Hex; +//import org.testng.Assert; +//import org.tron.common.runtime.TVMTestResult; +//import org.tron.common.runtime.TvmTestUtils; +//import org.tron.common.utils.StringUtil; +//import org.tron.common.utils.WalletUtil; +//import org.tron.core.exception.ContractExeException; +//import org.tron.core.exception.ContractValidateException; +//import org.tron.core.exception.ReceiptCheckErrException; +//import org.tron.core.exception.VMIllegalException; +//import org.tron.core.vm.config.ConfigLoader; +//import org.tron.core.vm.config.VMConfig; +//import org.tron.protos.Protocol.Transaction; +//import stest.tron.wallet.common.client.utils.AbiUtil; +// +//@Slf4j +//public class IsSRCandidateTest extends VMTestBase { +// +// /* +// pragma solidity ^0.5.0; +// +// contract ContractB{ +// address others; +// } +// +// contract TestIsSRCandidate{ +// address user; +// +// ContractB contractB = new ContractB(); +// +// constructor() public { +// user = msg.sender; +// } +// +// function isSRCandidateTest(address addr) public returns (bool) { +// return address(addr).isSRCandidate; +// } +// +// function nullAddressTest() public returns (bool) { +// return address(0x0).isSRCandidate; +// } +// +// function localContractAddrTest() public returns (bool) { +// address payable localContract = address(uint160(address(this))); +// return localContract.isSRCandidate; +// +// return address(this).isSRCandidate; +// } +// +// function otherContractAddrTest() public returns (bool) { +// return address(contractB).isSRCandidate; +// } +// +// function nonpayableAddrTest(address addr) public returns (bool) { +// return addr.isSRCandidate; +// } +// +// function payableAddrTest(address payable addr) public returns (bool) { +// return addr.isSRCandidate; +// } +// } +// */ +// +// @Test +// public void testIsSRCandidate() +// throws ContractExeException, ReceiptCheckErrException, VMIllegalException, +// ContractValidateException { +// ConfigLoader.disable = true; +// VMConfig.initAllowTvmTransferTrc10(1); +// VMConfig.initAllowTvmConstantinople(1); +// VMConfig.initAllowTvmSolidity059(1); +// VMConfig.initAllowTvmStake(1); +// String contractName = "TestIsSRCandidate"; +// byte[] address = Hex.decode(OWNER_ADDRESS); +// String abi = "[{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"constructor\"},{\"constant\":false," +// + "\"inputs\":[{\"internalType\":\"address\",\"name\":\"addr\"," +// + "\"type\":\"address\"}],\"name\":\"isSRCandidateTest\"," +// + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," +// + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," +// + "{\"constant\":false,\"inputs\":[],\"name\":\"localContractAddrTest\"," +// + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," +// + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," +// + "{\"constant\":false,\"inputs\":[{\"internalType\":\"address\"," +// + "\"name\":\"addr\",\"type\":\"address\"}],\"name\":\"nonpayableAddrTest\"," +// + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," +// + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," +// + "{\"constant\":false,\"inputs\":[],\"name\":\"nullAddressTest\"," +// + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," +// + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," +// + "{\"constant\":false,\"inputs\":[],\"name\":\"otherContractAddrTest\"," +// + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," +// + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," +// + "{\"constant\":false,\"inputs\":[{\"internalType\":\"address payable\"," +// + "\"name\":\"addr\",\"type\":\"address\"}],\"name\":\"payableAddrTest\"," +// + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," +// + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"; +// +// String factoryCode = "60806040526040516100109061008b565b6" +// + "04051809103906000f08015801561002c573d6000803e3d6" +// + "000fd5b50600180546001600160a01b0319166001600160a" +// + "01b039290921691909117905534801561005957600080fd5" +// + "b50d3801561006657600080fd5b50d280156100735760008" +// + "0fd5b50600080546001600160a01b0319163317905561009" +// + "7565b6072806101c283390190565b61011c806100a660003" +// + "96000f3fe6080604052348015600f57600080fd5b50d3801" +// + "5601b57600080fd5b50d28015602757600080fd5b5060043" +// + "61060725760003560e01c80632e48f1ac14607757806356b" +// + "42994146077578063627bfa45146077578063af4a1105146" +// + "0ae578063cb2d51cf1460b4578063d30a28ee1460ba575b6" +// + "00080fd5b609a60048036036020811015608b57600080fd5" +// + "b50356001600160a01b031660c0565b60408051911515825" +// + "2519081900360200190f35b609a60cd565b609a60d3565b6" +// + "09a60d8565b6001600160a01b0316d990565b6000d990565" +// + "b30d990565b6001546001600160a01b0316d99056fea2647" +// + "4726f6e5820509553fa5821ca76ddf8a0d074cd74dcb1f74" +// + "e068ca148b983f1b0bea447b99f64736f6c634300050d003" +// + "16080604052348015600f57600080fd5b50d38015601b576" +// + "00080fd5b50d28015602757600080fd5b50603d806035600" +// + "0396000f3fe6080604052600080fdfea26474726f6e58209" +// + "afab2d7a84ca331e2eb33393a62310b1a53e77c37a287407" +// + "53ae0a3a99980ba64736f6c634300050d0031"; +// long value = 0; +// long fee = 100000000; +// long consumeUserResourcePercent = 0; +// +// // deploy contract +// Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, +// null); +// byte[] factoryAddress = WalletUtil.generateContractAddress(trx); +// String factoryAddressStr = StringUtil.encode58Check(factoryAddress); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); +// Assert.assertNull(runtime.getRuntimeError()); +// +// // Trigger contract method: isSRCandidateTest(address) +// String methodByAddr = "isSRCandidateTest(address)"; +// String nonexistentAccount = "27k66nycZATHzBasFT9782nTsYWqVtxdtAc"; +// String hexInput = AbiUtil.parseMethod(methodByAddr, +// Collections.singletonList(nonexistentAccount)); +// TVMTestResult result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// byte[] returnValue = result.getRuntime().getResult().getHReturn(); +// // check deployed contract +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // trigger deployed contract +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// // check deployed contract +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // trigger deployed contract +// String witnessAccount = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(witnessAccount)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// // check deployed contract +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000001"); +// +// // Trigger contract method: nullAddressTest(address) +// methodByAddr = "nullAddressTest()"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// // check deployed contract +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // Trigger contract method: localContractAddrTest() +// methodByAddr = "localContractAddrTest()"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// // check deployed contract +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // Trigger contract method: otherContractAddrTest() +// methodByAddr = "otherContractAddrTest()"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// // check deployed contract +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // Trigger contract method: nonpayableAddrTest(address) +// methodByAddr = "nonpayableAddrTest(address)"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(witnessAccount)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// // check deployed contract +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000001"); +// +// // Trigger contract method: nonpayableAddrTest(address) +// methodByAddr = "nonpayableAddrTest(address)"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(nonexistentAccount)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// // check deployed contract +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // Trigger contract method: payableAddrTest(address) +// methodByAddr = "payableAddrTest(address)"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(nonexistentAccount)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// // check deployed contract +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// ConfigLoader.disable = false; +// } +//} +// +// diff --git a/framework/src/test/java/org/tron/common/runtime/vm/RewardBalanceTest.java b/framework/src/test/java/org/tron/common/runtime/vm/RewardBalanceTest.java index 9752174f650..4ae396ea988 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/RewardBalanceTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/RewardBalanceTest.java @@ -1,265 +1,265 @@ -package org.tron.common.runtime.vm; - -import java.util.Collections; -import lombok.extern.slf4j.Slf4j; -import org.junit.Test; -import org.spongycastle.util.encoders.Hex; -import org.testng.Assert; -import org.tron.common.runtime.TVMTestResult; -import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.WalletUtil; -import org.tron.core.exception.ContractExeException; -import org.tron.core.exception.ContractValidateException; -import org.tron.core.exception.ReceiptCheckErrException; -import org.tron.core.exception.VMIllegalException; -import org.tron.core.vm.config.ConfigLoader; -import org.tron.core.vm.config.VMConfig; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.utils.AbiUtil; - -@Slf4j -public class RewardBalanceTest extends VMTestBase { - - /* - pragma solidity ^0.5.0; - - contract ContractB{ - address user; - } - - contract TestRewardBalance{ - address user; - address payable owner; - - ContractB contractB = new ContractB(); - - constructor() public { - user = msg.sender; - } - - function rewardBalanceTest(address addr) view public returns (uint256) { - return addr.rewardbalance; - } - - function nullAddressTest() view public returns (uint256) { - return address(0x0).rewardbalance; - } - - function localContractAddrTest() view public returns (uint256) { - address payable localContract = address(uint160(address(this))); - return localContract.rewardbalance; - } - - function otherContractAddrTest() view public returns (uint256) { - address payable localContract = address(uint160(address(contractB))); - return localContract.rewardbalance; - } - - function nonpayableAddrTest(address addr) view public returns (uint256) { - return addr.rewardbalance; - } - - function payableAddrTest(address payable addr) view public returns (uint256) { - return addr.rewardbalance; - } - } - */ - - @Test - public void testRewardBalance() - throws ContractExeException, ReceiptCheckErrException, VMIllegalException, - ContractValidateException { - ConfigLoader.disable = true; - VMConfig.initAllowTvmTransferTrc10(1); - VMConfig.initAllowTvmConstantinople(1); - VMConfig.initAllowTvmSolidity059(1); - VMConfig.initAllowTvmStake(1); - manager.getDynamicPropertiesStore().saveChangeDelegation(1); - String contractName = "TestRewardBalance"; - byte[] address = Hex.decode(OWNER_ADDRESS); - String abi = "[{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\"," - + "\"type\":\"constructor\"},{\"constant\":false,\"inputs\":[]," - + "\"name\":\"localContractAddrTest\",\"outputs\":[{\"internalType\":\"uint256\"," - + "\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false," - + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," - + "\"inputs\":[{\"internalType\":\"address\",\"name\":\"addr\"," - + "\"type\":\"address\"}],\"name\":\"nonpayableAddrTest\"," - + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," - + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," - + "\"type\":\"function\"},{\"constant\":false,\"inputs\":[]," - + "\"name\":\"nullAddressTest\",\"outputs\":[{\"internalType\":\"uint256\"," - + "\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false," - + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," - + "\"inputs\":[],\"name\":\"otherContractAddrTest\"," - + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," - + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," - + "\"type\":\"function\"},{\"constant\":false," - + "\"inputs\":[{\"internalType\":\"address payable\",\"name\":\"addr\"," - + "\"type\":\"address\"}],\"name\":\"payableAddrTest\"," - + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," - + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," - + "\"type\":\"function\"},{\"constant\":false," - + "\"inputs\":[{\"internalType\":\"address\",\"name\":\"addr\"," - + "\"type\":\"address\"}],\"name\":\"rewardBalanceTest\"," - + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," - + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," - + "\"type\":\"function\"}]"; - String factoryCode = "60806040526040516100109061008b565b604051" - + "809103906000f08015801561002c573d6000803e3d6000fd5b506" - + "00280546001600160a01b0319166001600160a01b039290921691" - + "909117905534801561005957600080fd5b50d3801561006657600" - + "080fd5b50d2801561007357600080fd5b50600080546001600160" - + "a01b03191633179055610097565b6072806101c083390190565b6" - + "1011a806100a66000396000f3fe6080604052348015600f576000" - + "80fd5b50d38015601b57600080fd5b50d28015602757600080fd5" - + "b506004361060725760003560e01c806356b42994146077578063" - + "627bfa45146077578063a223c65f146077578063af4a11051460a" - + "c578063cb2d51cf1460b2578063d30a28ee1460b8575b600080fd" - + "5b609a60048036036020811015608b57600080fd5b50356001600" - + "160a01b031660be565b60408051918252519081900360200190f3" - + "5b609a60cb565b609a60d1565b609a60d6565b6001600160a01b0" - + "316d890565b6000d890565b30d890565b6002546001600160a01b" - + "0316d89056fea26474726f6e5820717344fa5eb84d711be29808c" - + "dff30740d75dddee7a38e76042a46157370501c64736f6c634300" - + "050d00316080604052348015600f57600080fd5b50d38015601b5" - + "7600080fd5b50d28015602757600080fd5b50603d806035600039" - + "6000f3fe6080604052600080fdfea26474726f6e582090ab77a1a" - + "2f65b0d6f77854c390b03b33fe20cd15ed8f722d497f9c3070c96" - + "ef64736f6c634300050d0031"; - long value = 0; - long fee = 100000000; - long consumeUserResourcePercent = 0; - - // deploy contract - Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, - null); - byte[] factoryAddress = WalletUtil.generateContractAddress(trx); - String factoryAddressStr = StringUtil.encode58Check(factoryAddress); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); - Assert.assertNull(runtime.getRuntimeError()); - - // Trigger contract method: rewardBalanceTest(address) - String methodByAddr = "rewardBalanceTest(address)"; - String nonexistentAccount = "27k66nycZATHzBasFT9782nTsYWqVtxdtAc"; - String hexInput = AbiUtil.parseMethod(methodByAddr, - Collections.singletonList(nonexistentAccount)); - TVMTestResult result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - byte[] returnValue = result.getRuntime().getResult().getHReturn(); - // check deployed contract - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // trigger deployed contract - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - // check deployed contract - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // trigger deployed contract - String witnessAccount = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(witnessAccount)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - // check deployed contract - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // Trigger contract method: nullAddressTest(address) - methodByAddr = "nullAddressTest()"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - // check deployed contract - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // Trigger contract method: localContractAddrTest() - methodByAddr = "localContractAddrTest()"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - // check deployed contract - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // Trigger contract method: otherContractAddrTest() - methodByAddr = "otherContractAddrTest()"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - // check deployed contract - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // Trigger contract method: nonpayableAddrTest(address) - methodByAddr = "nonpayableAddrTest(address)"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(witnessAccount)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - // check deployed contract - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // Trigger contract method: nonpayableAddrTest(address) - methodByAddr = "nonpayableAddrTest(address)"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(nonexistentAccount)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - // check deployed contract - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // Trigger contract method: payableAddrTest(address) - methodByAddr = "payableAddrTest(address)"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(nonexistentAccount)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - // check deployed contract - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - ConfigLoader.disable = false; - } -} - - +//package org.tron.common.runtime.vm; +// +//import java.util.Collections; +//import lombok.extern.slf4j.Slf4j; +//import org.junit.Test; +//import org.spongycastle.util.encoders.Hex; +//import org.testng.Assert; +//import org.tron.common.runtime.TVMTestResult; +//import org.tron.common.runtime.TvmTestUtils; +//import org.tron.common.utils.StringUtil; +//import org.tron.common.utils.WalletUtil; +//import org.tron.core.exception.ContractExeException; +//import org.tron.core.exception.ContractValidateException; +//import org.tron.core.exception.ReceiptCheckErrException; +//import org.tron.core.exception.VMIllegalException; +//import org.tron.core.vm.config.ConfigLoader; +//import org.tron.core.vm.config.VMConfig; +//import org.tron.protos.Protocol.Transaction; +//import stest.tron.wallet.common.client.utils.AbiUtil; +// +//@Slf4j +//public class RewardBalanceTest extends VMTestBase { +// +// /* +// pragma solidity ^0.5.0; +// +// contract ContractB{ +// address user; +// } +// +// contract TestRewardBalance{ +// address user; +// address payable owner; +// +// ContractB contractB = new ContractB(); +// +// constructor() public { +// user = msg.sender; +// } +// +// function rewardBalanceTest(address addr) view public returns (uint256) { +// return addr.rewardbalance; +// } +// +// function nullAddressTest() view public returns (uint256) { +// return address(0x0).rewardbalance; +// } +// +// function localContractAddrTest() view public returns (uint256) { +// address payable localContract = address(uint160(address(this))); +// return localContract.rewardbalance; +// } +// +// function otherContractAddrTest() view public returns (uint256) { +// address payable localContract = address(uint160(address(contractB))); +// return localContract.rewardbalance; +// } +// +// function nonpayableAddrTest(address addr) view public returns (uint256) { +// return addr.rewardbalance; +// } +// +// function payableAddrTest(address payable addr) view public returns (uint256) { +// return addr.rewardbalance; +// } +// } +// */ +// +// @Test +// public void testRewardBalance() +// throws ContractExeException, ReceiptCheckErrException, VMIllegalException, +// ContractValidateException { +// ConfigLoader.disable = true; +// VMConfig.initAllowTvmTransferTrc10(1); +// VMConfig.initAllowTvmConstantinople(1); +// VMConfig.initAllowTvmSolidity059(1); +// VMConfig.initAllowTvmStake(1); +// manager.getDynamicPropertiesStore().saveChangeDelegation(1); +// String contractName = "TestRewardBalance"; +// byte[] address = Hex.decode(OWNER_ADDRESS); +// String abi = "[{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"constructor\"},{\"constant\":false,\"inputs\":[]," +// + "\"name\":\"localContractAddrTest\",\"outputs\":[{\"internalType\":\"uint256\"," +// + "\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false," +// + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," +// + "\"inputs\":[{\"internalType\":\"address\",\"name\":\"addr\"," +// + "\"type\":\"address\"}],\"name\":\"nonpayableAddrTest\"," +// + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," +// + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"function\"},{\"constant\":false,\"inputs\":[]," +// + "\"name\":\"nullAddressTest\",\"outputs\":[{\"internalType\":\"uint256\"," +// + "\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false," +// + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," +// + "\"inputs\":[],\"name\":\"otherContractAddrTest\"," +// + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," +// + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"function\"},{\"constant\":false," +// + "\"inputs\":[{\"internalType\":\"address payable\",\"name\":\"addr\"," +// + "\"type\":\"address\"}],\"name\":\"payableAddrTest\"," +// + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," +// + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"function\"},{\"constant\":false," +// + "\"inputs\":[{\"internalType\":\"address\",\"name\":\"addr\"," +// + "\"type\":\"address\"}],\"name\":\"rewardBalanceTest\"," +// + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," +// + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"function\"}]"; +// String factoryCode = "60806040526040516100109061008b565b604051" +// + "809103906000f08015801561002c573d6000803e3d6000fd5b506" +// + "00280546001600160a01b0319166001600160a01b039290921691" +// + "909117905534801561005957600080fd5b50d3801561006657600" +// + "080fd5b50d2801561007357600080fd5b50600080546001600160" +// + "a01b03191633179055610097565b6072806101c083390190565b6" +// + "1011a806100a66000396000f3fe6080604052348015600f576000" +// + "80fd5b50d38015601b57600080fd5b50d28015602757600080fd5" +// + "b506004361060725760003560e01c806356b42994146077578063" +// + "627bfa45146077578063a223c65f146077578063af4a11051460a" +// + "c578063cb2d51cf1460b2578063d30a28ee1460b8575b600080fd" +// + "5b609a60048036036020811015608b57600080fd5b50356001600" +// + "160a01b031660be565b60408051918252519081900360200190f3" +// + "5b609a60cb565b609a60d1565b609a60d6565b6001600160a01b0" +// + "316d890565b6000d890565b30d890565b6002546001600160a01b" +// + "0316d89056fea26474726f6e5820717344fa5eb84d711be29808c" +// + "dff30740d75dddee7a38e76042a46157370501c64736f6c634300" +// + "050d00316080604052348015600f57600080fd5b50d38015601b5" +// + "7600080fd5b50d28015602757600080fd5b50603d806035600039" +// + "6000f3fe6080604052600080fdfea26474726f6e582090ab77a1a" +// + "2f65b0d6f77854c390b03b33fe20cd15ed8f722d497f9c3070c96" +// + "ef64736f6c634300050d0031"; +// long value = 0; +// long fee = 100000000; +// long consumeUserResourcePercent = 0; +// +// // deploy contract +// Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, +// null); +// byte[] factoryAddress = WalletUtil.generateContractAddress(trx); +// String factoryAddressStr = StringUtil.encode58Check(factoryAddress); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); +// Assert.assertNull(runtime.getRuntimeError()); +// +// // Trigger contract method: rewardBalanceTest(address) +// String methodByAddr = "rewardBalanceTest(address)"; +// String nonexistentAccount = "27k66nycZATHzBasFT9782nTsYWqVtxdtAc"; +// String hexInput = AbiUtil.parseMethod(methodByAddr, +// Collections.singletonList(nonexistentAccount)); +// TVMTestResult result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// byte[] returnValue = result.getRuntime().getResult().getHReturn(); +// // check deployed contract +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // trigger deployed contract +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// // check deployed contract +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // trigger deployed contract +// String witnessAccount = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(witnessAccount)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// // check deployed contract +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // Trigger contract method: nullAddressTest(address) +// methodByAddr = "nullAddressTest()"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// // check deployed contract +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // Trigger contract method: localContractAddrTest() +// methodByAddr = "localContractAddrTest()"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// // check deployed contract +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // Trigger contract method: otherContractAddrTest() +// methodByAddr = "otherContractAddrTest()"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// // check deployed contract +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // Trigger contract method: nonpayableAddrTest(address) +// methodByAddr = "nonpayableAddrTest(address)"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(witnessAccount)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// // check deployed contract +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // Trigger contract method: nonpayableAddrTest(address) +// methodByAddr = "nonpayableAddrTest(address)"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(nonexistentAccount)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// // check deployed contract +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // Trigger contract method: payableAddrTest(address) +// methodByAddr = "payableAddrTest(address)"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(nonexistentAccount)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// // check deployed contract +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// ConfigLoader.disable = false; +// } +//} +// +// diff --git a/framework/src/test/java/org/tron/common/runtime/vm/StakeTest.java b/framework/src/test/java/org/tron/common/runtime/vm/StakeTest.java index d2e75573ac5..5254014debf 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/StakeTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/StakeTest.java @@ -1,186 +1,186 @@ -package org.tron.common.runtime.vm; - -import java.util.Arrays; -import lombok.extern.slf4j.Slf4j; -import org.junit.Before; -import org.junit.Test; -import org.spongycastle.util.encoders.Hex; -import org.testng.Assert; -import org.tron.common.runtime.TVMTestResult; -import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.WalletUtil; -import org.tron.consensus.dpos.MaintenanceManager; -import org.tron.core.capsule.AccountCapsule; -import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.consensus.ConsensusService; -import org.tron.core.vm.config.ConfigLoader; -import org.tron.core.vm.config.VMConfig; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.utils.AbiUtil; - -@Slf4j -public class StakeTest extends VMTestBase { - private MaintenanceManager maintenanceManager; - - @Before - public void before() { - ConsensusService consensusService = context.getBean(ConsensusService.class); - consensusService.start(); - maintenanceManager = context.getBean(MaintenanceManager.class); - - ConfigLoader.disable = true; - VMConfig.initAllowTvmTransferTrc10(1); - VMConfig.initAllowTvmConstantinople(1); - VMConfig.initAllowTvmSolidity059(1); - VMConfig.initAllowTvmStake(1); - manager.getDynamicPropertiesStore().saveChangeDelegation(1); - } - /* -pragma solidity ^0.5.0; -contract TestStake{ - -constructor() payable public{} - -function selfdestructTest(address payable target) public{ - selfdestruct(target); -} - -function selfdestructTest2(address sr, uint256 amount, address payable target) public{ - stake(sr, amount); - selfdestruct(target); -} - -function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); -} -function UnStake() public returns (bool result){ - return unstake(); -} -} - */ - @Test - public void testStake() throws Exception { - String contractName = "TestStake"; - byte[] address = Hex.decode(OWNER_ADDRESS); - String abi = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":" - + "\"constructor\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"address\",\"name\"" - + ":\"sr\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\"," - + "\"type\":\"uint256\"}],\"name\":\"Stake\",\"outputs\":[{\"internalType\":\"bool\"" - + ",\"name\":\"result\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"" - + "nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"" - + "UnStake\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"result\",\"type\":\"" - + "bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}" - + ",{\"constant\":false,\"inputs\":[{\"internalType\":\"address payable\",\"name\":\"" - + "target\",\"type\":\"address\"}],\"name\":\"selfdestructTest\",\"outputs\":[],\"" - + "payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant" - + "\":false,\"inputs\":[{\"internalType\":\"address\",\"name\":\"sr\",\"type\":\"address" - + "\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"" - + "internalType\":\"address payable\",\"name\":\"target\",\"type\":\"address\"}],\"name" - + "\":\"selfdestructTest2\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"" - + "nonpayable\",\"type\":\"function\"}]"; - String factoryCode = "608060405261024a806100136000396000f3fe608060405234801561001057600080f" - + "d5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b50600436106100665760003560e01c8" - + "063377bdd4c1461006b57806338e8221f146100af578063ebedb8b31461011d578063ecb90615146101835" - + "75b600080fd5b6100ad6004803603602081101561008157600080fd5b81019080803573fffffffffffffff" - + "fffffffffffffffffffffffff1690602001909291905050506101a5565b005b61011b60048036036060811" - + "0156100c557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019" - + "092919080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909" - + "291905050506101be565b005b6101696004803603604081101561013357600080fd5b81019080803573fff" - + "fffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506101d" - + "b565b604051808215151515815260200191505060405180910390f35b61018b6101e8565b6040518082151" - + "51515815260200191505060405180910390f35b8073ffffffffffffffffffffffffffffffffffffffff16f" - + "f5b8183d5508073ffffffffffffffffffffffffffffffffffffffff16ff5b60008183d5905092915050565" - + "b6000d690509056fea26474726f6e582003e023985836e07a7f23202dfc410017c52159ee1ee3968435e99" - + "17f83f8d5a164736f6c637828302e352e31332d646576656c6f702e323032302e382e31332b636f6d6d697" - + "42e37633236393863300057"; - long feeLimit = 100000000; - - // deploy contract - Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - contractName, address, abi, factoryCode, 100000000, feeLimit, 0, - null); - byte[] factoryAddress = WalletUtil.generateContractAddress(trx); - String factoryAddressStr = StringUtil.encode58Check(factoryAddress); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); - Assert.assertNull(runtime.getRuntimeError()); - - - String methodByAddr = "Stake(address,uint256)"; - final String witnessAddrStr = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; - final byte[] witnessAddr = Hex.decode("a0299f3db80a24b20a254b89ce639d59132f157f13"); - // Trigger contract method - String hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList(witnessAddrStr, 10000000)); - TVMTestResult result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - byte[] returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000001"); - maintenanceManager.doMaintenance(); - AccountCapsule contract = manager.getAccountStore().get(factoryAddress); - WitnessCapsule witness = manager.getWitnessStore().get(witnessAddr); - Assert.assertEquals(contract.getFrozenCount(), 1); - Assert.assertEquals(contract.getFrozenBalance(), 10000000); - Assert.assertEquals(contract.getBalance(), 90000000); - Assert.assertEquals(contract.getVotesList().get(0).getVoteCount(), 10); - Assert.assertEquals(witness.getVoteCount(), 115); - - // Trigger contract method - hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList(witnessAddrStr, 5000000)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000001"); - contract = manager.getAccountStore().get(factoryAddress); - Assert.assertEquals(contract.getFrozenCount(), 1); - Assert.assertEquals(contract.getFrozenBalance(), 10000000); - Assert.assertEquals(contract.getVotesList().get(0).getVoteCount(), 5); - - // vote not exist witness - hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList( - "27k66nycZATHzBasFT9782nTsYWqVtxdtAc", 20000000)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - contract = manager.getAccountStore().get(factoryAddress); - Assert.assertEquals(contract.getBalance(), 90000000); - Assert.assertEquals(contract.getFrozenCount(), 1); - Assert.assertEquals(contract.getFrozenBalance(), 10000000); - - // param error - hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList( - "27k66nycZATHzBasFT9782nTsYWqVtxdtAc", -20000000)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // param error - hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList( - "27k66nycZATHzBasFT9782nTsYWqVtxdtAc", 2000000000)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - } -} +//package org.tron.common.runtime.vm; +// +//import java.util.Arrays; +//import lombok.extern.slf4j.Slf4j; +//import org.junit.Before; +//import org.junit.Test; +//import org.spongycastle.util.encoders.Hex; +//import org.testng.Assert; +//import org.tron.common.runtime.TVMTestResult; +//import org.tron.common.runtime.TvmTestUtils; +//import org.tron.common.utils.StringUtil; +//import org.tron.common.utils.WalletUtil; +//import org.tron.consensus.dpos.MaintenanceManager; +//import org.tron.core.capsule.AccountCapsule; +//import org.tron.core.capsule.WitnessCapsule; +//import org.tron.core.consensus.ConsensusService; +//import org.tron.core.vm.config.ConfigLoader; +//import org.tron.core.vm.config.VMConfig; +//import org.tron.protos.Protocol; +//import stest.tron.wallet.common.client.utils.AbiUtil; +// +//@Slf4j +//public class StakeTest extends VMTestBase { +// private MaintenanceManager maintenanceManager; +// +// @Before +// public void before() { +// ConsensusService consensusService = context.getBean(ConsensusService.class); +// consensusService.start(); +// maintenanceManager = context.getBean(MaintenanceManager.class); +// +// ConfigLoader.disable = true; +// VMConfig.initAllowTvmTransferTrc10(1); +// VMConfig.initAllowTvmConstantinople(1); +// VMConfig.initAllowTvmSolidity059(1); +// VMConfig.initAllowTvmStake(1); +// manager.getDynamicPropertiesStore().saveChangeDelegation(1); +// } +// /* +//pragma solidity ^0.5.0; +//contract TestStake{ +// +//constructor() payable public{} +// +//function selfdestructTest(address payable target) public{ +// selfdestruct(target); +//} +// +//function selfdestructTest2(address sr, uint256 amount, address payable target) public{ +// stake(sr, amount); +// selfdestruct(target); +//} +// +//function Stake(address sr, uint256 amount) public returns (bool result){ +// return stake(sr, amount); +//} +//function UnStake() public returns (bool result){ +// return unstake(); +//} +//} +// */ +// @Test +// public void testStake() throws Exception { +// String contractName = "TestStake"; +// byte[] address = Hex.decode(OWNER_ADDRESS); +// String abi = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":" +// + "\"constructor\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"address\",\"name\"" +// + ":\"sr\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\"," +// + "\"type\":\"uint256\"}],\"name\":\"Stake\",\"outputs\":[{\"internalType\":\"bool\"" +// + ",\"name\":\"result\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"" +// + "nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"" +// + "UnStake\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"result\",\"type\":\"" +// + "bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}" +// + ",{\"constant\":false,\"inputs\":[{\"internalType\":\"address payable\",\"name\":\"" +// + "target\",\"type\":\"address\"}],\"name\":\"selfdestructTest\",\"outputs\":[],\"" +// + "payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant" +// + "\":false,\"inputs\":[{\"internalType\":\"address\",\"name\":\"sr\",\"type\":\"address" +// + "\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"" +// + "internalType\":\"address payable\",\"name\":\"target\",\"type\":\"address\"}],\"name" +// + "\":\"selfdestructTest2\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"" +// + "nonpayable\",\"type\":\"function\"}]"; +// String factoryCode = "608060405261024a806100136000396000f3fe608060405234801561001057600080f" +// + "d5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b50600436106100665760003560e01c8" +// + "063377bdd4c1461006b57806338e8221f146100af578063ebedb8b31461011d578063ecb90615146101835" +// + "75b600080fd5b6100ad6004803603602081101561008157600080fd5b81019080803573fffffffffffffff" +// + "fffffffffffffffffffffffff1690602001909291905050506101a5565b005b61011b60048036036060811" +// + "0156100c557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019" +// + "092919080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909" +// + "291905050506101be565b005b6101696004803603604081101561013357600080fd5b81019080803573fff" +// + "fffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506101d" +// + "b565b604051808215151515815260200191505060405180910390f35b61018b6101e8565b6040518082151" +// + "51515815260200191505060405180910390f35b8073ffffffffffffffffffffffffffffffffffffffff16f" +// + "f5b8183d5508073ffffffffffffffffffffffffffffffffffffffff16ff5b60008183d5905092915050565" +// + "b6000d690509056fea26474726f6e582003e023985836e07a7f23202dfc410017c52159ee1ee3968435e99" +// + "17f83f8d5a164736f6c637828302e352e31332d646576656c6f702e323032302e382e31332b636f6d6d697" +// + "42e37633236393863300057"; +// long feeLimit = 100000000; +// +// // deploy contract +// Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// contractName, address, abi, factoryCode, 100000000, feeLimit, 0, +// null); +// byte[] factoryAddress = WalletUtil.generateContractAddress(trx); +// String factoryAddressStr = StringUtil.encode58Check(factoryAddress); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); +// Assert.assertNull(runtime.getRuntimeError()); +// +// +// String methodByAddr = "Stake(address,uint256)"; +// final String witnessAddrStr = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; +// final byte[] witnessAddr = Hex.decode("a0299f3db80a24b20a254b89ce639d59132f157f13"); +// // Trigger contract method +// String hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList(witnessAddrStr, 10000000)); +// TVMTestResult result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// byte[] returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000001"); +// maintenanceManager.doMaintenance(); +// AccountCapsule contract = manager.getAccountStore().get(factoryAddress); +// WitnessCapsule witness = manager.getWitnessStore().get(witnessAddr); +// Assert.assertEquals(contract.getFrozenCount(), 1); +// Assert.assertEquals(contract.getFrozenBalance(), 10000000); +// Assert.assertEquals(contract.getBalance(), 90000000); +// Assert.assertEquals(contract.getVotesList().get(0).getVoteCount(), 10); +// Assert.assertEquals(witness.getVoteCount(), 115); +// +// // Trigger contract method +// hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList(witnessAddrStr, 5000000)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000001"); +// contract = manager.getAccountStore().get(factoryAddress); +// Assert.assertEquals(contract.getFrozenCount(), 1); +// Assert.assertEquals(contract.getFrozenBalance(), 10000000); +// Assert.assertEquals(contract.getVotesList().get(0).getVoteCount(), 5); +// +// // vote not exist witness +// hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList( +// "27k66nycZATHzBasFT9782nTsYWqVtxdtAc", 20000000)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// contract = manager.getAccountStore().get(factoryAddress); +// Assert.assertEquals(contract.getBalance(), 90000000); +// Assert.assertEquals(contract.getFrozenCount(), 1); +// Assert.assertEquals(contract.getFrozenBalance(), 10000000); +// +// // param error +// hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList( +// "27k66nycZATHzBasFT9782nTsYWqVtxdtAc", -20000000)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // param error +// hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList( +// "27k66nycZATHzBasFT9782nTsYWqVtxdtAc", 2000000000)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// } +//} diff --git a/framework/src/test/java/org/tron/common/runtime/vm/SuicideTest.java b/framework/src/test/java/org/tron/common/runtime/vm/SuicideTest.java index 44a90bb93d2..cfb0b526050 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/SuicideTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/SuicideTest.java @@ -1,358 +1,358 @@ -package org.tron.common.runtime.vm; - -import java.util.Arrays; -import org.junit.Before; -import org.junit.Test; -import org.spongycastle.util.encoders.Hex; -import org.testng.Assert; -import org.tron.common.runtime.TVMTestResult; -import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.WalletUtil; -import org.tron.consensus.dpos.MaintenanceManager; -import org.tron.core.capsule.AccountCapsule; -import org.tron.core.capsule.VotesCapsule; -import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.consensus.ConsensusService; -import org.tron.core.db.TransactionTrace; -import org.tron.core.store.AccountStore; -import org.tron.core.store.VotesStore; -import org.tron.core.store.WitnessStore; -import org.tron.core.vm.config.ConfigLoader; -import org.tron.core.vm.config.VMConfig; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.utils.AbiUtil; - -public class SuicideTest extends VMTestBase { - - private MaintenanceManager maintenanceManager; - private AccountStore accountStore; - private WitnessStore witnessStore; - private VotesStore votesStore; - - @Before - public void before() { - ConsensusService consensusService = context.getBean(ConsensusService.class); - consensusService.start(); - maintenanceManager = context.getBean(MaintenanceManager.class); - accountStore = manager.getAccountStore(); - witnessStore = manager.getWitnessStore(); - votesStore = manager.getVotesStore(); - - ConfigLoader.disable = true; - VMConfig.initAllowTvmTransferTrc10(1); - VMConfig.initAllowTvmConstantinople(1); - VMConfig.initAllowTvmSolidity059(1); - VMConfig.initAllowTvmStake(1); - manager.getDynamicPropertiesStore().saveChangeDelegation(1); - } - /* -pragma solidity ^0.5.0; -contract TestStake{ - -constructor() payable public{} - -function selfdestructTest(address payable target) public{ -selfdestruct(target); -} - -function selfdestructTest2(address sr, uint256 amount, address payable target) public{ -stake(sr, amount); -selfdestruct(target); -} - -function Stake(address sr, uint256 amount) public returns (bool result){ -return stake(sr, amount); -} -function UnStake() public returns (bool result){ -return unstake(); -} -} -*/ - @Test - public void testSuicide() throws Exception { - String contractName = "TestSuicide"; - byte[] ownerAddress = Hex.decode(OWNER_ADDRESS); - String abi = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\"" - + ":\"constructor\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"address\",\"" - + "name\":\"sr\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount" - + "\",\"type\":\"uint256\"}],\"name\":\"Stake\",\"outputs\":[{\"internalType\":\"bool\"" - + ",\"name\":\"result\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"" - + "nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"" - + "UnStake\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"result\",\"type\":\"bool" - + "\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"" - + "constant\":false,\"inputs\":[{\"internalType\":\"address payable\",\"name\":\"target\"" - + ",\"type\":\"address\"}],\"name\":\"selfdestructTest\",\"outputs\":[],\"payable\":false" - + ",\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"" - + "inputs\":[{\"internalType\":\"address\",\"name\":\"sr\",\"type\":\"address\"},{\"" - + "internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"internalType\"" - + ":\"address payable\",\"name\":\"target\",\"type\":\"address\"}],\"name\":\"" - + "selfdestructTest2\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"" - + "nonpayable\",\"type\":\"function\"}]"; - String factoryCode = "608060405261024a806100136000396000f3fe608060405234801561001057600080" - + "fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b50600436106100665760003560e01" - + "c8063377bdd4c1461006b57806338e8221f146100af578063ebedb8b31461011d578063ecb90615146101" - + "83575b600080fd5b6100ad6004803603602081101561008157600080fd5b81019080803573fffffffffff" - + "fffffffffffffffffffffffffffff1690602001909291905050506101a5565b005b61011b600480360360" - + "608110156100c557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906" - + "020019092919080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060" - + "2001909291905050506101be565b005b6101696004803603604081101561013357600080fd5b810190808" - + "03573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050" - + "50506101db565b604051808215151515815260200191505060405180910390f35b61018b6101e8565b604" - + "051808215151515815260200191505060405180910390f35b8073ffffffffffffffffffffffffffffffff" - + "ffffffff16ff5b8183d5508073ffffffffffffffffffffffffffffffffffffffff16ff5b60008183d5905" - + "092915050565b6000d690509056fea26474726f6e582003e023985836e07a7f23202dfc410017c52159ee" - + "1ee3968435e9917f83f8d5a164736f6c637828302e352e31332d646576656c6f702e323032302e382e313" - + "32b636f6d6d69742e37633236393863300057"; - long feeLimit = 100000000; - - String witnessAddrStr = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; - final byte[] witnessAddr = Hex.decode("a0299f3db80a24b20a254b89ce639d59132f157f13"); - final String obtainUserAddrStr = "27k66nycZATHzBasFT9782nTsYWqVtxdtAc"; - final byte[] obtainUserAddr = Hex.decode("A0E6773BBF60F97D22AA3BF73D2FE235E816A1964F"); - - // suicide after stake (freeze not expire) - // deploy contract - Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - contractName, ownerAddress, abi, factoryCode, 100000000, feeLimit, 0, - null); - byte[] factoryAddress = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); - Assert.assertNull(runtime.getRuntimeError()); - String hexInput = AbiUtil.parseMethod("Stake(address,uint256)", - Arrays.asList(witnessAddrStr, 10000000)); - TVMTestResult result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - byte[] returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000001"); - Protocol.Account.Frozen frozen1; - frozen1 = accountStore.get(factoryAddress).getFrozenList().get(0); - //do maintain - maintenanceManager.doMaintenance(); - hexInput = AbiUtil.parseMethod("selfdestructTest(address)", Arrays.asList(obtainUserAddrStr)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - AccountCapsule obtainAccount = accountStore.get(obtainUserAddr); - Assert.assertEquals(obtainAccount.getBalance(), 90000000); - Assert.assertEquals(obtainAccount.getFrozenBalance(), 10000000); - Assert.assertEquals(obtainAccount.getFrozenList().get(0).getExpireTime(), - frozen1.getExpireTime()); - Assert.assertFalse(accountStore.has(factoryAddress)); - maintenanceManager.doMaintenance(); - WitnessCapsule witnessCapsule = witnessStore.get(witnessAddr); - Assert.assertEquals(witnessCapsule.getVoteCount(), 105); - Assert.assertEquals(obtainAccount.getVotesList().size(), 0); - - // suicide to a staked account - trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - contractName, ownerAddress, abi, factoryCode, 100000000, feeLimit, 0, - null); - factoryAddress = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); - Assert.assertNull(runtime.getRuntimeError()); - hexInput = AbiUtil.parseMethod("Stake(address,uint256)", - Arrays.asList(witnessAddrStr, 10000000)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000001"); - frozen1 = accountStore.get(factoryAddress).getFrozenList().get(0); - maintenanceManager.doMaintenance(); - Protocol.Account.Frozen frozen2; - frozen2 = accountStore.get(obtainUserAddr).getFrozenList().get(0); - hexInput = AbiUtil.parseMethod("selfdestructTest(address)", Arrays.asList(obtainUserAddrStr)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - obtainAccount = accountStore.get(obtainUserAddr); - Assert.assertEquals(obtainAccount.getBalance(), 180000000); - Assert.assertEquals(obtainAccount.getFrozenBalance(), 20000000); - Assert.assertEquals(obtainAccount.getFrozenList().get(0).getExpireTime(), - (frozen1.getExpireTime() * frozen1.getFrozenBalance() - + frozen2.getExpireTime() * frozen2.getFrozenBalance()) - / (frozen1.getFrozenBalance() + frozen2.getFrozenBalance())); - - //test suicide to staked contract & suicide to itself - final long totalNetWeightStart = manager.getDynamicPropertiesStore().getTotalNetWeight(); - //deploy contract1 - trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - contractName, ownerAddress, abi, factoryCode, 100000000, feeLimit, 0, - null); - factoryAddress = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); - Assert.assertNull(runtime.getRuntimeError()); - //deploy contract obtain - trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - "contractObtain", ownerAddress, abi, factoryCode, 100000000, feeLimit, 0, - null); - byte[] obtainContractAddr = WalletUtil.generateContractAddress(trx); - String obtainContractAddrStr; - obtainContractAddrStr = StringUtil.encode58Check(obtainContractAddr); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); - Assert.assertNull(runtime.getRuntimeError()); - //factoryAddress Stake - hexInput = AbiUtil.parseMethod("Stake(address,uint256)", - Arrays.asList(witnessAddrStr, 10000000)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000001"); - //obtainContractAddr Stake - hexInput = AbiUtil.parseMethod("Stake(address,uint256)", - Arrays.asList(witnessAddrStr, 10000000)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - obtainContractAddr, Hex.decode(hexInput), 0, feeLimit, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000001"); - frozen1 = accountStore.get(factoryAddress).getFrozenList().get(0); - frozen2 = accountStore.get(obtainContractAddr).getFrozenList().get(0); - maintenanceManager.doMaintenance(); - //factoryAddress suicide - hexInput = AbiUtil.parseMethod("selfdestructTest(address)", - Arrays.asList(obtainContractAddrStr)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - obtainAccount = accountStore.get(obtainContractAddr); - Assert.assertEquals(obtainAccount.getBalance(), 180000000); - Assert.assertEquals(obtainAccount.getFrozenBalance(), 20000000); - Assert.assertEquals(obtainAccount.getFrozenList().get(0).getExpireTime(), - (frozen1.getExpireTime() * frozen1.getFrozenBalance() - + frozen2.getExpireTime() * frozen2.getFrozenBalance()) - / (frozen1.getFrozenBalance() + frozen2.getFrozenBalance())); - Assert.assertEquals(manager.getDynamicPropertiesStore().getTotalNetWeight(), - totalNetWeightStart + 20); - //obtainContractAddr suicide to itself - AccountCapsule blackHoleAccount; - blackHoleAccount = accountStore.getBlackhole(); - hexInput = AbiUtil.parseMethod("selfdestructTest(address)", - Arrays.asList(obtainContractAddrStr)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - obtainContractAddr, Hex.decode(hexInput), 0, feeLimit, manager, null); - AccountCapsule blackHoleAccountAfter = accountStore.getBlackhole(); - Assert.assertNull(result.getRuntime().getRuntimeError()); - Assert.assertEquals(blackHoleAccountAfter.getBalance(), 200000000 - + blackHoleAccount.getBalance() + 25500); // 25500 for energy used for suicide - Assert.assertEquals(blackHoleAccountAfter.getFrozenBalance(), 0); - Assert.assertEquals(manager.getDynamicPropertiesStore().getTotalNetWeight(), - totalNetWeightStart); - - //test vote - final byte[] zeroAddr = TransactionTrace.convertToTronAddress(new byte[20]); - //deploy contract1 - trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - contractName, ownerAddress, abi, factoryCode, 100000000, feeLimit, 0, - null); - factoryAddress = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); - Assert.assertNull(runtime.getRuntimeError()); - //deploy contract obtain - trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - "contractObtain", ownerAddress, abi, factoryCode, 100000000, feeLimit, 0, - null); - obtainContractAddr = WalletUtil.generateContractAddress(trx); - obtainContractAddrStr = StringUtil.encode58Check(obtainContractAddr); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); - Assert.assertNull(runtime.getRuntimeError()); - //deploy contract2 - trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - "contractSuicide", ownerAddress, abi, factoryCode, 100000000, feeLimit, 0, - null); - byte[] suicideContractAddr = WalletUtil.generateContractAddress(trx); - String suicideContractAddrStr = StringUtil.encode58Check(suicideContractAddr); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); - Assert.assertNull(runtime.getRuntimeError()); - //factoryAddress Stake - hexInput = AbiUtil.parseMethod("Stake(address,uint256)", - Arrays.asList(witnessAddrStr, 10000000)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000001"); - //obtainContractAddr Stake - hexInput = AbiUtil.parseMethod("Stake(address,uint256)", - Arrays.asList(witnessAddrStr, 10000000)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - obtainContractAddr, Hex.decode(hexInput), 0, feeLimit, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000001"); - //suicideContractAddr Stake - hexInput = AbiUtil.parseMethod("Stake(address,uint256)", - Arrays.asList(witnessAddrStr, 10000000)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - suicideContractAddr, Hex.decode(hexInput), 0, feeLimit, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000001"); - maintenanceManager.doMaintenance(); - Assert.assertEquals(accountStore.get(factoryAddress).getVotesList().get(0).getVoteCount(), 10); - Assert.assertEquals(accountStore.get(obtainContractAddr) - .getVotesList().get(0).getVoteCount(), 10); - Assert.assertEquals(accountStore.get(suicideContractAddr) - .getVotesList().get(0).getVoteCount(), 10); - Assert.assertEquals(witnessStore.get(witnessAddr).getVoteCount(), 105 + 30); - //contract1 suicide - hexInput = AbiUtil.parseMethod("selfdestructTest(address)", - Arrays.asList(obtainContractAddrStr)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - Assert.assertEquals(accountStore.get(obtainContractAddr).getBalance(), 180000000); - VotesCapsule zeroVotes = votesStore.get(zeroAddr); - Assert.assertEquals(zeroVotes.getOldVotes().get(0).getVoteCount(), 10); - Assert.assertEquals(zeroVotes.getNewVotes().size(), 0); - //suicideContractAddr Stake - hexInput = AbiUtil.parseMethod("Stake(address,uint256)", - Arrays.asList(witnessAddrStr, 5000000)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - suicideContractAddr, Hex.decode(hexInput), 0, feeLimit, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000001"); - VotesCapsule suicideContractVotes = votesStore.get(suicideContractAddr); - Assert.assertEquals(suicideContractVotes.getOldVotes().get(0).getVoteCount(), 10); - Assert.assertEquals(suicideContractVotes.getNewVotes().get(0).getVoteCount(), 5); - //suicideContractAddr suicide - hexInput = AbiUtil.parseMethod("selfdestructTest(address)", - Arrays.asList(obtainContractAddrStr)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - suicideContractAddr, Hex.decode(hexInput), 0, feeLimit, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - Assert.assertEquals(accountStore.get(obtainContractAddr).getBalance(), 270000000); - zeroVotes = votesStore.get(zeroAddr); - Assert.assertEquals(zeroVotes.getOldVotes().get(0).getVoteCount(), 20); - Assert.assertEquals(zeroVotes.getNewVotes().size(), 0); - Assert.assertFalse(votesStore.has(suicideContractAddr)); - maintenanceManager.doMaintenance(); - Assert.assertEquals(witnessStore.get(witnessAddr).getVoteCount(), 105 + 10); - } -} +//package org.tron.common.runtime.vm; +// +//import java.util.Arrays; +//import org.junit.Before; +//import org.junit.Test; +//import org.spongycastle.util.encoders.Hex; +//import org.testng.Assert; +//import org.tron.common.runtime.TVMTestResult; +//import org.tron.common.runtime.TvmTestUtils; +//import org.tron.common.utils.StringUtil; +//import org.tron.common.utils.WalletUtil; +//import org.tron.consensus.dpos.MaintenanceManager; +//import org.tron.core.capsule.AccountCapsule; +//import org.tron.core.capsule.VotesCapsule; +//import org.tron.core.capsule.WitnessCapsule; +//import org.tron.core.consensus.ConsensusService; +//import org.tron.core.db.TransactionTrace; +//import org.tron.core.store.AccountStore; +//import org.tron.core.store.VotesStore; +//import org.tron.core.store.WitnessStore; +//import org.tron.core.vm.config.ConfigLoader; +//import org.tron.core.vm.config.VMConfig; +//import org.tron.protos.Protocol; +//import stest.tron.wallet.common.client.utils.AbiUtil; +// +//public class SuicideTest extends VMTestBase { +// +// private MaintenanceManager maintenanceManager; +// private AccountStore accountStore; +// private WitnessStore witnessStore; +// private VotesStore votesStore; +// +// @Before +// public void before() { +// ConsensusService consensusService = context.getBean(ConsensusService.class); +// consensusService.start(); +// maintenanceManager = context.getBean(MaintenanceManager.class); +// accountStore = manager.getAccountStore(); +// witnessStore = manager.getWitnessStore(); +// votesStore = manager.getVotesStore(); +// +// ConfigLoader.disable = true; +// VMConfig.initAllowTvmTransferTrc10(1); +// VMConfig.initAllowTvmConstantinople(1); +// VMConfig.initAllowTvmSolidity059(1); +// VMConfig.initAllowTvmStake(1); +// manager.getDynamicPropertiesStore().saveChangeDelegation(1); +// } +// /* +//pragma solidity ^0.5.0; +//contract TestStake{ +// +//constructor() payable public{} +// +//function selfdestructTest(address payable target) public{ +//selfdestruct(target); +//} +// +//function selfdestructTest2(address sr, uint256 amount, address payable target) public{ +//stake(sr, amount); +//selfdestruct(target); +//} +// +//function Stake(address sr, uint256 amount) public returns (bool result){ +//return stake(sr, amount); +//} +//function UnStake() public returns (bool result){ +//return unstake(); +//} +//} +//*/ +// @Test +// public void testSuicide() throws Exception { +// String contractName = "TestSuicide"; +// byte[] ownerAddress = Hex.decode(OWNER_ADDRESS); +// String abi = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\"" +// + ":\"constructor\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"address\",\"" +// + "name\":\"sr\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount" +// + "\",\"type\":\"uint256\"}],\"name\":\"Stake\",\"outputs\":[{\"internalType\":\"bool\"" +// + ",\"name\":\"result\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"" +// + "nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"" +// + "UnStake\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"result\",\"type\":\"bool" +// + "\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"" +// + "constant\":false,\"inputs\":[{\"internalType\":\"address payable\",\"name\":\"target\"" +// + ",\"type\":\"address\"}],\"name\":\"selfdestructTest\",\"outputs\":[],\"payable\":false" +// + ",\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"" +// + "inputs\":[{\"internalType\":\"address\",\"name\":\"sr\",\"type\":\"address\"},{\"" +// + "internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"},{\"internalType\"" +// + ":\"address payable\",\"name\":\"target\",\"type\":\"address\"}],\"name\":\"" +// + "selfdestructTest2\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"" +// + "nonpayable\",\"type\":\"function\"}]"; +// String factoryCode = "608060405261024a806100136000396000f3fe608060405234801561001057600080" +// + "fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b50600436106100665760003560e01" +// + "c8063377bdd4c1461006b57806338e8221f146100af578063ebedb8b31461011d578063ecb90615146101" +// + "83575b600080fd5b6100ad6004803603602081101561008157600080fd5b81019080803573fffffffffff" +// + "fffffffffffffffffffffffffffff1690602001909291905050506101a5565b005b61011b600480360360" +// + "608110156100c557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906" +// + "020019092919080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060" +// + "2001909291905050506101be565b005b6101696004803603604081101561013357600080fd5b810190808" +// + "03573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050" +// + "50506101db565b604051808215151515815260200191505060405180910390f35b61018b6101e8565b604" +// + "051808215151515815260200191505060405180910390f35b8073ffffffffffffffffffffffffffffffff" +// + "ffffffff16ff5b8183d5508073ffffffffffffffffffffffffffffffffffffffff16ff5b60008183d5905" +// + "092915050565b6000d690509056fea26474726f6e582003e023985836e07a7f23202dfc410017c52159ee" +// + "1ee3968435e9917f83f8d5a164736f6c637828302e352e31332d646576656c6f702e323032302e382e313" +// + "32b636f6d6d69742e37633236393863300057"; +// long feeLimit = 100000000; +// +// String witnessAddrStr = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; +// final byte[] witnessAddr = Hex.decode("a0299f3db80a24b20a254b89ce639d59132f157f13"); +// final String obtainUserAddrStr = "27k66nycZATHzBasFT9782nTsYWqVtxdtAc"; +// final byte[] obtainUserAddr = Hex.decode("A0E6773BBF60F97D22AA3BF73D2FE235E816A1964F"); +// +// // suicide after stake (freeze not expire) +// // deploy contract +// Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// contractName, ownerAddress, abi, factoryCode, 100000000, feeLimit, 0, +// null); +// byte[] factoryAddress = WalletUtil.generateContractAddress(trx); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); +// Assert.assertNull(runtime.getRuntimeError()); +// String hexInput = AbiUtil.parseMethod("Stake(address,uint256)", +// Arrays.asList(witnessAddrStr, 10000000)); +// TVMTestResult result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// byte[] returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000001"); +// Protocol.Account.Frozen frozen1; +// frozen1 = accountStore.get(factoryAddress).getFrozenList().get(0); +// //do maintain +// maintenanceManager.doMaintenance(); +// hexInput = AbiUtil.parseMethod("selfdestructTest(address)", Arrays.asList(obtainUserAddrStr)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// AccountCapsule obtainAccount = accountStore.get(obtainUserAddr); +// Assert.assertEquals(obtainAccount.getBalance(), 90000000); +// Assert.assertEquals(obtainAccount.getFrozenBalance(), 10000000); +// Assert.assertEquals(obtainAccount.getFrozenList().get(0).getExpireTime(), +// frozen1.getExpireTime()); +// Assert.assertFalse(accountStore.has(factoryAddress)); +// maintenanceManager.doMaintenance(); +// WitnessCapsule witnessCapsule = witnessStore.get(witnessAddr); +// Assert.assertEquals(witnessCapsule.getVoteCount(), 105); +// Assert.assertEquals(obtainAccount.getVotesList().size(), 0); +// +// // suicide to a staked account +// trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// contractName, ownerAddress, abi, factoryCode, 100000000, feeLimit, 0, +// null); +// factoryAddress = WalletUtil.generateContractAddress(trx); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); +// Assert.assertNull(runtime.getRuntimeError()); +// hexInput = AbiUtil.parseMethod("Stake(address,uint256)", +// Arrays.asList(witnessAddrStr, 10000000)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000001"); +// frozen1 = accountStore.get(factoryAddress).getFrozenList().get(0); +// maintenanceManager.doMaintenance(); +// Protocol.Account.Frozen frozen2; +// frozen2 = accountStore.get(obtainUserAddr).getFrozenList().get(0); +// hexInput = AbiUtil.parseMethod("selfdestructTest(address)", Arrays.asList(obtainUserAddrStr)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// obtainAccount = accountStore.get(obtainUserAddr); +// Assert.assertEquals(obtainAccount.getBalance(), 180000000); +// Assert.assertEquals(obtainAccount.getFrozenBalance(), 20000000); +// Assert.assertEquals(obtainAccount.getFrozenList().get(0).getExpireTime(), +// (frozen1.getExpireTime() * frozen1.getFrozenBalance() +// + frozen2.getExpireTime() * frozen2.getFrozenBalance()) +// / (frozen1.getFrozenBalance() + frozen2.getFrozenBalance())); +// +// //test suicide to staked contract & suicide to itself +// final long totalNetWeightStart = manager.getDynamicPropertiesStore().getTotalNetWeight(); +// //deploy contract1 +// trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// contractName, ownerAddress, abi, factoryCode, 100000000, feeLimit, 0, +// null); +// factoryAddress = WalletUtil.generateContractAddress(trx); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); +// Assert.assertNull(runtime.getRuntimeError()); +// //deploy contract obtain +// trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// "contractObtain", ownerAddress, abi, factoryCode, 100000000, feeLimit, 0, +// null); +// byte[] obtainContractAddr = WalletUtil.generateContractAddress(trx); +// String obtainContractAddrStr; +// obtainContractAddrStr = StringUtil.encode58Check(obtainContractAddr); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); +// Assert.assertNull(runtime.getRuntimeError()); +// //factoryAddress Stake +// hexInput = AbiUtil.parseMethod("Stake(address,uint256)", +// Arrays.asList(witnessAddrStr, 10000000)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000001"); +// //obtainContractAddr Stake +// hexInput = AbiUtil.parseMethod("Stake(address,uint256)", +// Arrays.asList(witnessAddrStr, 10000000)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// obtainContractAddr, Hex.decode(hexInput), 0, feeLimit, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000001"); +// frozen1 = accountStore.get(factoryAddress).getFrozenList().get(0); +// frozen2 = accountStore.get(obtainContractAddr).getFrozenList().get(0); +// maintenanceManager.doMaintenance(); +// //factoryAddress suicide +// hexInput = AbiUtil.parseMethod("selfdestructTest(address)", +// Arrays.asList(obtainContractAddrStr)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// obtainAccount = accountStore.get(obtainContractAddr); +// Assert.assertEquals(obtainAccount.getBalance(), 180000000); +// Assert.assertEquals(obtainAccount.getFrozenBalance(), 20000000); +// Assert.assertEquals(obtainAccount.getFrozenList().get(0).getExpireTime(), +// (frozen1.getExpireTime() * frozen1.getFrozenBalance() +// + frozen2.getExpireTime() * frozen2.getFrozenBalance()) +// / (frozen1.getFrozenBalance() + frozen2.getFrozenBalance())); +// Assert.assertEquals(manager.getDynamicPropertiesStore().getTotalNetWeight(), +// totalNetWeightStart + 20); +// //obtainContractAddr suicide to itself +// AccountCapsule blackHoleAccount; +// blackHoleAccount = accountStore.getBlackhole(); +// hexInput = AbiUtil.parseMethod("selfdestructTest(address)", +// Arrays.asList(obtainContractAddrStr)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// obtainContractAddr, Hex.decode(hexInput), 0, feeLimit, manager, null); +// AccountCapsule blackHoleAccountAfter = accountStore.getBlackhole(); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// Assert.assertEquals(blackHoleAccountAfter.getBalance(), 200000000 +// + blackHoleAccount.getBalance() + 25500); // 25500 for energy used for suicide +// Assert.assertEquals(blackHoleAccountAfter.getFrozenBalance(), 0); +// Assert.assertEquals(manager.getDynamicPropertiesStore().getTotalNetWeight(), +// totalNetWeightStart); +// +// //test vote +// final byte[] zeroAddr = TransactionTrace.convertToTronAddress(new byte[20]); +// //deploy contract1 +// trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// contractName, ownerAddress, abi, factoryCode, 100000000, feeLimit, 0, +// null); +// factoryAddress = WalletUtil.generateContractAddress(trx); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); +// Assert.assertNull(runtime.getRuntimeError()); +// //deploy contract obtain +// trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// "contractObtain", ownerAddress, abi, factoryCode, 100000000, feeLimit, 0, +// null); +// obtainContractAddr = WalletUtil.generateContractAddress(trx); +// obtainContractAddrStr = StringUtil.encode58Check(obtainContractAddr); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); +// Assert.assertNull(runtime.getRuntimeError()); +// //deploy contract2 +// trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// "contractSuicide", ownerAddress, abi, factoryCode, 100000000, feeLimit, 0, +// null); +// byte[] suicideContractAddr = WalletUtil.generateContractAddress(trx); +// String suicideContractAddrStr = StringUtil.encode58Check(suicideContractAddr); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); +// Assert.assertNull(runtime.getRuntimeError()); +// //factoryAddress Stake +// hexInput = AbiUtil.parseMethod("Stake(address,uint256)", +// Arrays.asList(witnessAddrStr, 10000000)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000001"); +// //obtainContractAddr Stake +// hexInput = AbiUtil.parseMethod("Stake(address,uint256)", +// Arrays.asList(witnessAddrStr, 10000000)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// obtainContractAddr, Hex.decode(hexInput), 0, feeLimit, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000001"); +// //suicideContractAddr Stake +// hexInput = AbiUtil.parseMethod("Stake(address,uint256)", +// Arrays.asList(witnessAddrStr, 10000000)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// suicideContractAddr, Hex.decode(hexInput), 0, feeLimit, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000001"); +// maintenanceManager.doMaintenance(); +// Assert.assertEquals(accountStore.get(factoryAddress).getVotesList().get(0).getVoteCount(), 10); +// Assert.assertEquals(accountStore.get(obtainContractAddr) +// .getVotesList().get(0).getVoteCount(), 10); +// Assert.assertEquals(accountStore.get(suicideContractAddr) +// .getVotesList().get(0).getVoteCount(), 10); +// Assert.assertEquals(witnessStore.get(witnessAddr).getVoteCount(), 105 + 30); +// //contract1 suicide +// hexInput = AbiUtil.parseMethod("selfdestructTest(address)", +// Arrays.asList(obtainContractAddrStr)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// Assert.assertEquals(accountStore.get(obtainContractAddr).getBalance(), 180000000); +// VotesCapsule zeroVotes = votesStore.get(zeroAddr); +// Assert.assertEquals(zeroVotes.getOldVotes().get(0).getVoteCount(), 10); +// Assert.assertEquals(zeroVotes.getNewVotes().size(), 0); +// //suicideContractAddr Stake +// hexInput = AbiUtil.parseMethod("Stake(address,uint256)", +// Arrays.asList(witnessAddrStr, 5000000)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// suicideContractAddr, Hex.decode(hexInput), 0, feeLimit, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000001"); +// VotesCapsule suicideContractVotes = votesStore.get(suicideContractAddr); +// Assert.assertEquals(suicideContractVotes.getOldVotes().get(0).getVoteCount(), 10); +// Assert.assertEquals(suicideContractVotes.getNewVotes().get(0).getVoteCount(), 5); +// //suicideContractAddr suicide +// hexInput = AbiUtil.parseMethod("selfdestructTest(address)", +// Arrays.asList(obtainContractAddrStr)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// suicideContractAddr, Hex.decode(hexInput), 0, feeLimit, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// Assert.assertEquals(accountStore.get(obtainContractAddr).getBalance(), 270000000); +// zeroVotes = votesStore.get(zeroAddr); +// Assert.assertEquals(zeroVotes.getOldVotes().get(0).getVoteCount(), 20); +// Assert.assertEquals(zeroVotes.getNewVotes().size(), 0); +// Assert.assertFalse(votesStore.has(suicideContractAddr)); +// maintenanceManager.doMaintenance(); +// Assert.assertEquals(witnessStore.get(witnessAddr).getVoteCount(), 105 + 10); +// } +//} diff --git a/framework/src/test/java/org/tron/common/runtime/vm/Trc10Test.java b/framework/src/test/java/org/tron/common/runtime/vm/Trc10Test.java index 3beda866ffd..a433ba4f8ae 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/Trc10Test.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/Trc10Test.java @@ -1,659 +1,659 @@ -package org.tron.common.runtime.vm; - -import static stest.tron.wallet.common.client.utils.PublicMethed.decode58Check; - -import java.util.Arrays; -import java.util.Collections; -import lombok.extern.slf4j.Slf4j; -import org.junit.Test; -import org.spongycastle.util.encoders.Hex; -import org.testng.Assert; -import org.tron.common.runtime.TVMTestResult; -import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.WalletUtil; -import org.tron.core.exception.ContractExeException; -import org.tron.core.exception.ContractValidateException; -import org.tron.core.exception.ReceiptCheckErrException; -import org.tron.core.exception.VMIllegalException; -import org.tron.core.vm.config.ConfigLoader; -import org.tron.core.vm.config.VMConfig; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.utils.AbiUtil; - -@Slf4j -public class Trc10Test extends VMContractTestBase { - - /*pragma solidity ^0.5.12; - contract HelloWorld{ - function TokenIssue(bytes32 name, bytes32 abbr, uint64 - totalSupply, uint8 precision) public returns (uint) { - return assetissue(name, abbr, totalSupply, precision); - } - function UpdateAsset(trcToken tokenId, string memory url, string - memory desc) public { - updateasset(tokenId, bytes(url), bytes(desc)); - } - }*/ - @Test - public void testTrc10Validate() throws ContractExeException, - ReceiptCheckErrException, VMIllegalException, - ContractValidateException { - ConfigLoader.disable = true; - VMConfig.initAllowTvmTransferTrc10(1); - VMConfig.initAllowTvmConstantinople(1); - VMConfig.initAllowTvmSolidity059(1); - VMConfig.initAllowTvmAssetIssue(1); - manager.getDynamicPropertiesStore().saveAllowSameTokenName(1); - String contractName = "AssetIssueTest"; - byte[] address = Hex.decode(OWNER_ADDRESS); - String abi = "[{\"constant\":false," - + "\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"name\"," - + "\"type\":\"bytes32\"},{\"internalType\":\"bytes32\"," - + "\"name\":\"abbr\",\"type\":\"bytes32\"}," - + "{\"internalType\":\"uint64\",\"name\":\"totalSupply\"," - + "\"type\":\"uint64\"},{\"internalType\":\"uint8\"," - + "\"name\":\"precision\",\"type\":\"uint8\"}]," - + "\"name\":\"TokenIssue\"," - + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," - + "\"type\":\"uint256\"}],\"payable\":false," - + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," - + "{\"constant\":false,\"inputs\":[{\"internalType\":\"trcToken" - + "\",\"name\":\"tokenId\",\"type\":\"trcToken\"}," - + "{\"internalType\":\"string\",\"name\":\"desc\"," - + "\"type\":\"string\"},{\"internalType\":\"string\"," - + "\"name\":\"url\",\"type\":\"string\"}]," - + "\"name\":\"UpdateAsset\",\"outputs\":[],\"payable\":false," - + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"; - String factoryCode = - "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a576000" - + "80fd5b506102938061003a6000396000f3fe608060405234801561001057600080fd5b50d3801561" - + "001d57600080fd5b50d2801561002a57600080fd5b50600436106100505760003560e01c80633615" - + "673e14610055578063f177bc7a146100c2575b600080fd5b6100ac6004803603608081101561006b" - + "57600080fd5b810190808035906020019092919080359060200190929190803567ffffffffffffff" - + "ff169060200190929190803560ff16906020019092919050505061021e565b604051808281526020" - + "0191505060405180910390f35b61021c600480360360608110156100d857600080fd5b8101908080" - + "359060200190929190803590602001906401000000008111156100ff57600080fd5b820183602082" - + "01111561011157600080fd5b80359060200191846001830284011164010000000083111715610133" - + "57600080fd5b91908080601f01602080910402602001604051908101604052809392919081815260" - + "2001838380828437600081840152601f19601f820116905080830192505050505050509192919290" - + "8035906020019064010000000081111561019657600080fd5b8201836020820111156101a8576000" - + "80fd5b803590602001918460018302840111640100000000831117156101ca57600080fd5b919080" - + "80601f01602080910402602001604051908101604052809392919081815260200183838082843760" - + "0081840152601f19601f82011690508083019250505050505050919291929050505061022f565b00" - + "5b600081838587da9050949350505050565b808284db5050505056fea26474726f6e5820def53e9f" - + "ef23475f8f3316cfaf66a0015e2205fe9bf0eba01f703e30ef9d732364736f6c637828302e352e31" - + "332d646576656c6f702e323032302e382e31332b636f6d6d69742e37633236393863300057"; - long value = 0; - long fee = 100000000; - long consumeUserResourcePercent = 0; - // deploy contract - Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, - null); - byte[] factoryAddress = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); - Assert.assertNull(runtime.getRuntimeError()); - - // validate balance is enough - String tokenP1 = "74657374"; - String tokenP2 = tokenP1; - long tokenP3 = 1000; - long tokenP4 = 2; - String methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8)"; - String hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP2, - tokenP3, tokenP4)); - TVMTestResult result = - TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, - Hex.decode(hexInput), value, fee, manager, null); - Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 0); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - rootRepository.addBalance(factoryAddress, 10000000000L); - rootRepository.commit(); - Assert.assertEquals(rootRepository.getBalance(factoryAddress), 10000000000L); - - // validate assetissue assetname can't be trx - tokenP1 = "747278"; - tokenP2 = tokenP1; - tokenP3 = 1000; - tokenP4 = 2; - methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8)"; - hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP2, tokenP3, - tokenP4)); - result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, - Hex.decode(hexInput), value, fee, manager, null); - Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 0); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - // validate assetissue precision can't more than 6 - tokenP1 = "74657374"; - tokenP2 = tokenP1; - tokenP3 = 1000; - tokenP4 = 7; - methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8)"; - hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP2, tokenP3, - tokenP4)); - result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, - Hex.decode(hexInput), value, fee, manager, null); - Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 0); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - // trigger contract success - tokenP1 = "74657374"; - tokenP2 = tokenP1; - tokenP3 = 1000; - tokenP4 = 2; - methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8)"; - hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP2, tokenP3, - tokenP4)); - result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, - Hex.decode(hexInput), value, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 1000001); - long expectEnergyUsageTotal = 25000; - long expectEnergyUsageTotalMax = 30000; - long reallyEnergyUsageTotal = result.getReceipt().getEnergyUsageTotal(); - // validate energy cost - Assert.assertTrue(reallyEnergyUsageTotal > expectEnergyUsageTotal - && reallyEnergyUsageTotal < expectEnergyUsageTotalMax); - - // validate assetissue An account can only issue one asset - tokenP1 = "74657374"; - tokenP2 = tokenP1; - tokenP3 = 1000; - tokenP4 = 2; - methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8)"; - hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP2, tokenP3, - tokenP4)); - result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, - Hex.decode(hexInput), value, fee, manager, null); - Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 0); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - // Trigger contract method: UpdateAsset(trcToken, string, string) - String methodUpdateAsset = "UpdateAsset(trcToken,string,string)"; - // 1,abc,abc, - long updateP1 = 1000001; - String updateP2 = "abc"; - String updateP3 = updateP2; - hexInput = AbiUtil.parseMethod(methodUpdateAsset, Arrays.asList(updateP1, updateP2, updateP3)); - result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, - Hex.decode(hexInput), value, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() - .get(0).getUrl().toByteArray()), "abc"); - Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() - .get(0).getDesc().toByteArray()), "abc"); - // validate energy cost - expectEnergyUsageTotal = 5000; - expectEnergyUsageTotalMax = 10000; - reallyEnergyUsageTotal = result.getReceipt().getEnergyUsageTotal(); - - Assert.assertTrue(reallyEnergyUsageTotal > expectEnergyUsageTotal - && reallyEnergyUsageTotal < expectEnergyUsageTotalMax); - - // validate desc less than 200 - updateP1 = 1000001; - updateP2 = - "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcab" - + "cabcabcabcabcabcabcababcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcab" - + "cabcabcabcabcabcabcabcabcabcabcabcabcabcababcabcabcabcabcabcabcabcabcabcabcabcab" - + "cabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcababcabcabcabcabcab" - + "cabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabca" - + "bcab"; - updateP3 = "efg"; - hexInput = AbiUtil.parseMethod(methodUpdateAsset, Arrays.asList(updateP1, updateP2, updateP3)); - result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, - Hex.decode(hexInput), value, fee, manager, null); - Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() - .get(0).getUrl().toByteArray()), "abc"); - Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() - .get(0).getDesc().toByteArray()), "abc"); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - // validate url less than 256 - updateP1 = 1000001; - updateP3 = - "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcab" - + "cabcabcabcabcabcabcaabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc" - + "abcabcabcabcabcabcabcabcabcabcabcabcabcaabcabcabcabcabcabcabcabcabcabcabcabcabca" - + "bcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcaabcabcabcabcabcabcab" - + "cabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabca"; - updateP2 = "efg"; - hexInput = AbiUtil.parseMethod(methodUpdateAsset, Arrays.asList(updateP1, updateP2, updateP3)); - result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, - Hex.decode(hexInput), value, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - } - - /*pragma solidity ^0.5.12; - contract HelloWorld{ - function TokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) - public { - assetissue(name, abbr, totalSupply, precision); - assetissue(name, abbr, totalSupply, precision); - } - function UpdateAsset(trcToken tokenId, string memory url, string memory desc) public { - updateasset(tokenId, bytes(url), bytes(desc)); - updateasset(tokenId, bytes(url), bytes(desc)); - } - }*/ - - @Test - public void testTrc10ForMultiCall() throws ContractExeException, - ReceiptCheckErrException, VMIllegalException, - ContractValidateException { - ConfigLoader.disable = true; - VMConfig.initAllowTvmTransferTrc10(1); - VMConfig.initAllowTvmConstantinople(1); - VMConfig.initAllowTvmSolidity059(1); - VMConfig.initAllowTvmAssetIssue(1); - manager.getDynamicPropertiesStore().saveAllowSameTokenName(1); - String contractName = "AssetIssueTest"; - byte[] address = Hex.decode(OWNER_ADDRESS); - String abi = "[{\"constant\":false,\"inputs\":[{\"internalType\":\"bytes32\"," - + "\"name\":\"name\"," - + "\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"abbr\"," - + "\"type\":\"bytes32\"}," - + "{\"internalType\":\"uint64\",\"name\":\"totalSupply\",\"type\":\"uint64\"}," - + "{\"internalType\":\"uint8\",\"name\":\"precision\",\"type\":\"uint8\"}]," - + "\"name\":\"TokenIssue\"," - + "\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\"," - + "\"type\":\"function\"}," - + "{\"constant\":false,\"inputs\":[{\"internalType\":\"trcToken\",\"name\":\"tokenId\"," - + "\"type\":\"trcToken\"},{\"internalType\":\"string\",\"name\":\"desc\"," - + "\"type\":\"string\"}," - + "{\"internalType\":\"string\",\"name\":\"url\",\"type\":\"string\"}]," - + "\"name\":\"UpdateAsset\"," - + "\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\"," - + "\"type\":\"function\"}]"; - String factoryCode = - "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a576000" - + "80fd5b506102858061003a6000396000f3fe608060405234801561001057600080fd5b50d3801561" - + "001d57600080fd5b50d2801561002a57600080fd5b50600436106100505760003560e01c80633615" - + "673e14610055578063f177bc7a146100ae575b600080fd5b6100ac6004803603608081101561006b" - + "57600080fd5b810190808035906020019092919080359060200190929190803567ffffffffffffff" - + "ff169060200190929190803560ff16906020019092919050505061020a565b005b61020860048036" - + "0360608110156100c457600080fd5b81019080803590602001909291908035906020019064010000" - + "00008111156100eb57600080fd5b8201836020820111156100fd57600080fd5b8035906020019184" - + "600183028401116401000000008311171561011f57600080fd5b91908080601f0160208091040260" - + "20016040519081016040528093929190818152602001838380828437600081840152601f19601f82" - + "01169050808301925050505050505091929192908035906020019064010000000081111561018257" - + "600080fd5b82018360208201111561019457600080fd5b8035906020019184600183028401116401" - + "00000000831117156101b657600080fd5b91908080601f0160208091040260200160405190810160" - + "40528093929190818152602001838380828437600081840152601f19601f82011690508083019250" - + "505050505050919291929050505061021c565b005b80828486da5080828486da5050505050565b80" - + "8284db50808284db5050505056fea26474726f6e582010b72c10cc2d93a0ddc6ec14e8a40345f73a" - + "2263120bd04e1552687570eb950c64736f6c637828302e352e31332d646576656c6f702e32303230" - + "2e382e31332b636f6d6d69742e37633236393863300057"; - long value = 0; - long fee = 100000000; - long consumeUserResourcePercent = 0; - // deploy contract - Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, - null); - byte[] factoryAddress = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); - Assert.assertNull(runtime.getRuntimeError()); - - // send coin - rootRepository.addBalance(factoryAddress, 10000000000L); - rootRepository.commit(); - Assert.assertEquals(rootRepository.getBalance(factoryAddress), 10000000000L); - - // validate updateasset Asset is not existed in AssetIssueStore - String methodUpdateAsset = "UpdateAsset(trcToken,string,string)"; - // 1,abc,abc, - long updateP1 = 1000001; - String updateP2 = "616263"; - String updateP3 = updateP2; - String hexInput = AbiUtil.parseMethod(methodUpdateAsset, Arrays.asList(updateP1, updateP2, - updateP3)); - TVMTestResult result = - TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, - Hex.decode(hexInput), value, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - // multicall tokenissue - String tokenP1 = "74657374"; - long tokenP3 = 1000; - long tokenP4 = 2; - String methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8)"; - hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP1, tokenP3, - tokenP4)); - result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, - Hex.decode(hexInput), value, fee, manager, null); - Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 0); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - // multicall updateAsset - methodUpdateAsset = "UpdateAsset(trcToken,string,string)"; - // 1,abc,abc, - updateP1 = 1000001; - updateP2 = "abc"; - updateP3 = updateP2; - hexInput = AbiUtil.parseMethod(methodUpdateAsset, Arrays.asList(updateP1, updateP2, updateP3)); - result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, - Hex.decode(hexInput), value, fee, manager, null); - Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() - .get(0).getUrl().toByteArray()), - "abc"); - Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() - .get(0).getDesc().toByteArray()), - "abc"); - Assert.assertNull(result.getRuntime().getRuntimeError()); - } - - /*pragma solidity ^0.5.12; - contract HelloWorld{ - function TokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision, - address addr) public { - address payable newaddress = address(uint160(addr)); - newaddress.transfer(100000000); - assetissue(name, abbr, totalSupply, precision); - newaddress.transfer(100000000); - } - function UpdateAsset(trcToken tokenId, string memory url, string memory desc, address - addr) public { - address payable newaddress = address(uint160(addr)); - newaddress.transfer(100000000); - updateasset(tokenId, bytes(url), bytes(desc)); - newaddress.transfer(100000000); - } - }*/ - - @Test - public void testTrc10Exception() throws ContractExeException, - ReceiptCheckErrException, VMIllegalException, - ContractValidateException { - ConfigLoader.disable = true; - VMConfig.initAllowTvmTransferTrc10(1); - VMConfig.initAllowTvmConstantinople(1); - VMConfig.initAllowTvmSolidity059(1); - VMConfig.initAllowTvmAssetIssue(1); - String contractName = "AssetIssueTest"; - byte[] address = Hex.decode(OWNER_ADDRESS); - String abi = "[{\"constant\":false,\"inputs\":[{\"internalType\":\"bytes32\"," - + "\"name\":\"name\"," - + "\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"abbr\"," - + "\"type\":\"bytes32\"}," - + "{\"internalType\":\"uint64\",\"name\":\"totalSupply\",\"type\":\"uint64\"}," - + "{\"internalType\":\"uint8\",\"name\":\"precision\",\"type\":\"uint8\"}," - + "{\"internalType\":\"address\",\"name\":\"addr\",\"type\":\"address\"}]," - + "\"name\":\"TokenIssue\"," - + "\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\"," - + "\"type\":\"function\"}," - + "{\"constant\":false,\"inputs\":[{\"internalType\":\"trcToken\",\"name\":\"tokenId\"," - + "\"type\":\"trcToken\"},{\"internalType\":\"string\",\"name\":\"desc\"," - + "\"type\":\"string\"}," - + "{\"internalType\":\"string\",\"name\":\"url\",\"type\":\"string\"}," - + "{\"internalType\":\"address\"," - + "\"name\":\"addr\",\"type\":\"address\"}],\"name\":\"UpdateAsset\",\"outputs\":[]," - + "\"payable\":false," - + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"; - String factoryCode = - "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a576000" - + "80fd5b506103f48061003a6000396000f3fe608060405234801561001057600080fd5b50d3801561" - + "001d57600080fd5b50d2801561002a57600080fd5b50600436106100505760003560e01c8063451e" - + "cfa214610055578063a241e431146100ce575b600080fd5b6100cc600480360360a081101561006b" - + "57600080fd5b810190808035906020019092919080359060200190929190803567ffffffffffffff" - + "ff169060200190929190803560ff169060200190929190803573ffffffffffffffffffffffffffff" - + "ffffffffffff16906020019092919050505061024a565b005b610248600480360360808110156100" - + "e457600080fd5b81019080803590602001909291908035906020019064010000000081111561010b" - + "57600080fd5b82018360208201111561011d57600080fd5b80359060200191846001830284011164" - + "01000000008311171561013f57600080fd5b91908080601f01602080910402602001604051908101" - + "6040528093929190818152602001838380828437600081840152601f19601f820116905080830192" - + "505050505050509192919290803590602001906401000000008111156101a257600080fd5b820183" - + "6020820111156101b457600080fd5b80359060200191846001830284011164010000000083111715" - + "6101d657600080fd5b91908080601f01602080910402602001604051908101604052809392919081" - + "8152602001838380828437600081840152601f19601f820116905080830192505050505050509192" - + "919290803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506102" - + "f3565b005b60008190508073ffffffffffffffffffffffffffffffffffffffff166108fc6305f5e1" - + "009081150290604051600060405180830381858888f19350505050158015610299573d6000803e3d" - + "6000fd5b5082848688da508073ffffffffffffffffffffffffffffffffffffffff166108fc6305f5" - + "e1009081150290604051600060405180830381858888f193505050501580156102ea573d6000803e" - + "3d6000fd5b50505050505050565b60008190508073ffffffffffffffffffffffffffffffffffffff" - + "ff166108fc6305f5e1009081150290604051600060405180830381858888f1935050505015801561" - + "0342573d6000803e3d6000fd5b50828486db508073ffffffffffffffffffffffffffffffffffffff" - + "ff166108fc6305f5e1009081150290604051600060405180830381858888f1935050505015801561" - + "0392573d6000803e3d6000fd5b50505050505056fea26474726f6e5820e6e64fe3d21e1866d8b2da" - + "9e9bba20e7b5fee47cf6122aae388eb63b4d3df07264736f6c637828302e352e31332d646576656c" - + "6f702e323032302e382e31332b636f6d6d69742e37633236393863300057"; - long value = 0; - long fee = 100000000; - long consumeUserResourcePercent = 0; - // deploy contract - Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, - null); - byte[] factoryAddress = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); - Assert.assertNull(runtime.getRuntimeError()); - - // sendcoin to factoryAddress 100000000000 - rootRepository.addBalance(factoryAddress, 10000000000L); - rootRepository.commit(); - Assert.assertEquals(rootRepository.getBalance(factoryAddress), 10000000000L); - - // assetissue exception test - String tokenP1 = "74657374"; - long tokenP3 = 1000; - long tokenP4 = 7; - String methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8,address)"; - String receiveAddress = "27VZHn9PFZwNh7o2EporxmLkpe157iWZVkh"; - String hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP1, - tokenP3, tokenP4, receiveAddress)); - TVMTestResult result = - TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, - Hex.decode(hexInput), value, fee, manager, null); - Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 0); - Assert.assertNull(result.getRuntime().getRuntimeError()); - Assert.assertEquals(200000000, - rootRepository.getBalance(decode58Check(receiveAddress))); - - // updateasset exception test - String methodUpdateAsset = "UpdateAsset(trcToken,string,string,address)"; - // 1,abc,abc, - long updateP1 = 1000001; - String updateP2 = "616263"; - hexInput = AbiUtil.parseMethod(methodUpdateAsset, Arrays.asList(updateP1, updateP2, updateP2, - receiveAddress)); - result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, - Hex.decode(hexInput), value, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - Assert.assertEquals(200000000, rootRepository.getBalance(decode58Check(receiveAddress))); - } - - /*pragma solidity ^0.5.0; - contract A { - function TokenIssueA(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) - public returns (uint){ - return assetissue(name, abbr, totalSupply, precision); - } - function UpdateAssetA(trcToken tokenId, string memory desc, string memory url) public { - updateasset(tokenId, bytes(desc), bytes(url)); - } - } - contract HelloWorld { - A a = new A(); - function TokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) - public returns (uint) { - return a.TokenIssueA(name, abbr, totalSupply, precision); - } - function UpdateAsset(trcToken tokenId, string memory url, string memory desc) public { - a.UpdateAssetA(tokenId, url, desc); - } - function getContractAddress() public returns (address) { - return address(a); - } - }*/ - - @Test - public void testTrc10ContractCall() throws ContractExeException, - ReceiptCheckErrException, VMIllegalException, - ContractValidateException { - ConfigLoader.disable = true; - VMConfig.initAllowTvmTransferTrc10(1); - VMConfig.initAllowTvmConstantinople(1); - VMConfig.initAllowTvmSolidity059(1); - VMConfig.initAllowTvmAssetIssue(1); - manager.getDynamicPropertiesStore().saveAllowSameTokenName(1); - String contractName = "AssetIssueTest"; - byte[] address = Hex.decode(OWNER_ADDRESS); - String abi = "[{\"constant\":false,\"inputs\":[{\"internalType\":\"bytes32\"," - + "\"name\":\"name\"," - + "\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"abbr\"," - + "\"type\":\"bytes32\"}," - + "{\"internalType\":\"uint64\",\"name\":\"totalSupply\",\"type\":\"uint64\"}," - + "{\"internalType\":\"uint8\",\"name\":\"precision\",\"type\":\"uint8\"}]," - + "\"name\":\"TokenIssue\"," - + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}]," - + "\"payable\":false," - + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," - + "\"inputs\":[{\"internalType\":\"trcToken\",\"name\":\"tokenId\",\"type\":\"trcToken\"}," - + "{\"internalType\":\"string\",\"name\":\"desc\",\"type\":\"string\"}," - + "{\"internalType\":\"string\"," - + "\"name\":\"url\",\"type\":\"string\"}],\"name\":\"UpdateAsset\",\"outputs\":[]," - + "\"payable\":false," - + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," - + "\"inputs\":[]," - + "\"name\":\"getContractAddress\",\"outputs\":[{\"internalType\":\"address\"," - + "\"name\":\"\"," - + "\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," - + "\"type\":\"function\"}]"; - String factoryCode = - "608060405260405161001090610098565b604051809103906000f08015801561002c573d6000803e" - + "3d6000fd5b506000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916" - + "908373ffffffffffffffffffffffffffffffffffffffff16021790555034801561007857600080fd" - + "5b50d3801561008557600080fd5b50d2801561009257600080fd5b506100a5565b6102cd80610602" - + "83390190565b61054e806100b46000396000f3fe608060405234801561001057600080fd5b50d380" - + "1561001d57600080fd5b50d2801561002a57600080fd5b506004361061005b5760003560e01c8063" - + "32a2c5d0146100605780633615673e146100aa578063f177bc7a14610117575b600080fd5b610068" - + "610273565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffff" - + "ffffffffffffffffffffffffff16815260200191505060405180910390f35b610101600480360360" - + "808110156100c057600080fd5b810190808035906020019092919080359060200190929190803567" - + "ffffffffffffffff169060200190929190803560ff16906020019092919050505061029c565b6040" - + "518082815260200191505060405180910390f35b6102716004803603606081101561012d57600080" - + "fd5b81019080803590602001909291908035906020019064010000000081111561015457600080fd" - + "5b82018360208201111561016657600080fd5b803590602001918460018302840111640100000000" - + "8311171561018857600080fd5b91908080601f016020809104026020016040519081016040528093" - + "929190818152602001838380828437600081840152601f19601f8201169050808301925050505050" - + "50509192919290803590602001906401000000008111156101eb57600080fd5b8201836020820111" - + "156101fd57600080fd5b8035906020019184600183028401116401000000008311171561021f5760" - + "0080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001" - + "838380828437600081840152601f19601f8201169050808301925050505050505091929192905050" - + "50610389565b005b60008060009054906101000a900473ffffffffffffffffffffffffffffffffff" - + "ffffff16905090565b60008060009054906101000a900473ffffffffffffffffffffffffffffffff" - + "ffffffff1673ffffffffffffffffffffffffffffffffffffffff166329f00e598686868660405185" - + "63ffffffff1660e01b8152600401808581526020018481526020018367ffffffffffffffff1667ff" - + "ffffffffffffff1681526020018260ff1660ff168152602001945050505050602060405180830381" - + "600087803b15801561034457600080fd5b505af1158015610358573d6000803e3d6000fd5b505050" - + "506040513d602081101561036e57600080fd5b810190808051906020019092919050505090509493" - + "50505050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff16" - + "73ffffffffffffffffffffffffffffffffffffffff1663cfa62e758484846040518463ffffffff16" - + "60e01b81526004018084815260200180602001806020018381038352858181518152602001915080" - + "51906020019080838360005b83811015610422578082015181840152602081019050610407565b50" - + "505050905090810190601f16801561044f5780820380516001836020036101000a03191681526020" - + "0191505b50838103825284818151815260200191508051906020019080838360005b838110156104" - + "8857808201518184015260208101905061046d565b50505050905090810190601f1680156104b557" - + "80820380516001836020036101000a031916815260200191505b5095505050505050600060405180" - + "830381600087803b1580156104d757600080fd5b505af11580156104eb573d6000803e3d6000fd5b" - + "5050505050505056fea26474726f6e582068c6e59329c5b9e63f34ea5762d58db8649b294831356a" - + "dfe323a04f3c96c25f64736f6c637828302e352e31332d646576656c6f702e323032302e382e3133" - + "2b636f6d6d69742e37633236393863300057608060405234801561001057600080fd5b50d3801561" - + "001d57600080fd5b50d2801561002a57600080fd5b506102938061003a6000396000f3fe60806040" - + "5234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b50" - + "600436106100505760003560e01c806329f00e5914610055578063cfa62e75146100c2575b600080" - + "fd5b6100ac6004803603608081101561006b57600080fd5b81019080803590602001909291908035" - + "9060200190929190803567ffffffffffffffff169060200190929190803560ff1690602001909291" - + "9050505061021e565b6040518082815260200191505060405180910390f35b61021c600480360360" - + "608110156100d857600080fd5b810190808035906020019092919080359060200190640100000000" - + "8111156100ff57600080fd5b82018360208201111561011157600080fd5b80359060200191846001" - + "83028401116401000000008311171561013357600080fd5b91908080601f01602080910402602001" - + "6040519081016040528093929190818152602001838380828437600081840152601f19601f820116" - + "90508083019250505050505050919291929080359060200190640100000000811115610196576000" - + "80fd5b8201836020820111156101a857600080fd5b80359060200191846001830284011164010000" - + "0000831117156101ca57600080fd5b91908080601f01602080910402602001604051908101604052" - + "8093929190818152602001838380828437600081840152601f19601f820116905080830192505050" - + "50505050919291929050505061022f565b005b600081838587da9050949350505050565b808284db" - + "5050505056fea26474726f6e582071af66a376cfd560797ad3c889d08b9037d8ec121805b96fd252" - + "3415b77f4df264736f6c637828302e352e31332d646576656c6f702e323032302e382e31332b636f" - + "6d6d69742e37633236393863300057"; - long value = 0; - long fee = 100000000; - long consumeUserResourcePercent = 0; - // deploy contract - Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, - null); - byte[] factoryAddress = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); - Assert.assertNull(runtime.getRuntimeError()); - - // Trigger contract method: getContractAddress() - String methodByAddr = "getContractAddress()"; - String hexInput = AbiUtil.parseMethod(methodByAddr, Collections.emptyList()); - TVMTestResult result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - byte[] returnValue = result.getRuntime().getResult().getHReturn(); - - // Contract A Address - String tmpAddress = "a0" + Hex.toHexString(returnValue).substring(24); - - // sendcoin to A address 100000000000 - rootRepository.addBalance(ByteArray.fromHexString(tmpAddress), 10000000000L); - rootRepository.commit(); - Assert.assertEquals(rootRepository.getBalance(ByteArray.fromHexString(tmpAddress)), - 10000000000L); - - // assetissue test - String tokenP1 = "74657374"; - long tokenP3 = 1000; - long tokenP4 = 2; - String methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8)"; - hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP1, tokenP3, - tokenP4)); - result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, - Hex.decode(hexInput), value, fee, manager, null); - Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 1000001); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - // updateasset test - String methodUpdateAsset = "UpdateAsset(trcToken,string,string)"; - // 1,abc,abc, - long updateP1 = 1000001; - String updateP2 = "abc"; - hexInput = AbiUtil.parseMethod(methodUpdateAsset, Arrays.asList(updateP1, updateP2, updateP2)); - result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, - Hex.decode(hexInput), value, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() - .get(0).getUrl().toByteArray()), - "abc"); - Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() - .get(0).getDesc().toByteArray()), - "abc"); - } -} - - - +//package org.tron.common.runtime.vm; +// +//import static stest.tron.wallet.common.client.utils.PublicMethed.decode58Check; +// +//import java.util.Arrays; +//import java.util.Collections; +//import lombok.extern.slf4j.Slf4j; +//import org.junit.Test; +//import org.spongycastle.util.encoders.Hex; +//import org.testng.Assert; +//import org.tron.common.runtime.TVMTestResult; +//import org.tron.common.runtime.TvmTestUtils; +//import org.tron.common.utils.ByteArray; +//import org.tron.common.utils.WalletUtil; +//import org.tron.core.exception.ContractExeException; +//import org.tron.core.exception.ContractValidateException; +//import org.tron.core.exception.ReceiptCheckErrException; +//import org.tron.core.exception.VMIllegalException; +//import org.tron.core.vm.config.ConfigLoader; +//import org.tron.core.vm.config.VMConfig; +//import org.tron.protos.Protocol; +//import stest.tron.wallet.common.client.utils.AbiUtil; +// +//@Slf4j +//public class Trc10Test extends VMContractTestBase { +// +// /*pragma solidity ^0.5.12; +// contract HelloWorld{ +// function TokenIssue(bytes32 name, bytes32 abbr, uint64 +// totalSupply, uint8 precision) public returns (uint) { +// return assetissue(name, abbr, totalSupply, precision); +// } +// function UpdateAsset(trcToken tokenId, string memory url, string +// memory desc) public { +// updateasset(tokenId, bytes(url), bytes(desc)); +// } +// }*/ +// @Test +// public void testTrc10Validate() throws ContractExeException, +// ReceiptCheckErrException, VMIllegalException, +// ContractValidateException { +// ConfigLoader.disable = true; +// VMConfig.initAllowTvmTransferTrc10(1); +// VMConfig.initAllowTvmConstantinople(1); +// VMConfig.initAllowTvmSolidity059(1); +// VMConfig.initAllowTvmAssetIssue(1); +// manager.getDynamicPropertiesStore().saveAllowSameTokenName(1); +// String contractName = "AssetIssueTest"; +// byte[] address = Hex.decode(OWNER_ADDRESS); +// String abi = "[{\"constant\":false," +// + "\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"name\"," +// + "\"type\":\"bytes32\"},{\"internalType\":\"bytes32\"," +// + "\"name\":\"abbr\",\"type\":\"bytes32\"}," +// + "{\"internalType\":\"uint64\",\"name\":\"totalSupply\"," +// + "\"type\":\"uint64\"},{\"internalType\":\"uint8\"," +// + "\"name\":\"precision\",\"type\":\"uint8\"}]," +// + "\"name\":\"TokenIssue\"," +// + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," +// + "\"type\":\"uint256\"}],\"payable\":false," +// + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," +// + "{\"constant\":false,\"inputs\":[{\"internalType\":\"trcToken" +// + "\",\"name\":\"tokenId\",\"type\":\"trcToken\"}," +// + "{\"internalType\":\"string\",\"name\":\"desc\"," +// + "\"type\":\"string\"},{\"internalType\":\"string\"," +// + "\"name\":\"url\",\"type\":\"string\"}]," +// + "\"name\":\"UpdateAsset\",\"outputs\":[],\"payable\":false," +// + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"; +// String factoryCode = +// "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a576000" +// + "80fd5b506102938061003a6000396000f3fe608060405234801561001057600080fd5b50d3801561" +// + "001d57600080fd5b50d2801561002a57600080fd5b50600436106100505760003560e01c80633615" +// + "673e14610055578063f177bc7a146100c2575b600080fd5b6100ac6004803603608081101561006b" +// + "57600080fd5b810190808035906020019092919080359060200190929190803567ffffffffffffff" +// + "ff169060200190929190803560ff16906020019092919050505061021e565b604051808281526020" +// + "0191505060405180910390f35b61021c600480360360608110156100d857600080fd5b8101908080" +// + "359060200190929190803590602001906401000000008111156100ff57600080fd5b820183602082" +// + "01111561011157600080fd5b80359060200191846001830284011164010000000083111715610133" +// + "57600080fd5b91908080601f01602080910402602001604051908101604052809392919081815260" +// + "2001838380828437600081840152601f19601f820116905080830192505050505050509192919290" +// + "8035906020019064010000000081111561019657600080fd5b8201836020820111156101a8576000" +// + "80fd5b803590602001918460018302840111640100000000831117156101ca57600080fd5b919080" +// + "80601f01602080910402602001604051908101604052809392919081815260200183838082843760" +// + "0081840152601f19601f82011690508083019250505050505050919291929050505061022f565b00" +// + "5b600081838587da9050949350505050565b808284db5050505056fea26474726f6e5820def53e9f" +// + "ef23475f8f3316cfaf66a0015e2205fe9bf0eba01f703e30ef9d732364736f6c637828302e352e31" +// + "332d646576656c6f702e323032302e382e31332b636f6d6d69742e37633236393863300057"; +// long value = 0; +// long fee = 100000000; +// long consumeUserResourcePercent = 0; +// // deploy contract +// Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, +// null); +// byte[] factoryAddress = WalletUtil.generateContractAddress(trx); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); +// Assert.assertNull(runtime.getRuntimeError()); +// +// // validate balance is enough +// String tokenP1 = "74657374"; +// String tokenP2 = tokenP1; +// long tokenP3 = 1000; +// long tokenP4 = 2; +// String methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8)"; +// String hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP2, +// tokenP3, tokenP4)); +// TVMTestResult result = +// TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 0); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// rootRepository.addBalance(factoryAddress, 10000000000L); +// rootRepository.commit(); +// Assert.assertEquals(rootRepository.getBalance(factoryAddress), 10000000000L); +// +// // validate assetissue assetname can't be trx +// tokenP1 = "747278"; +// tokenP2 = tokenP1; +// tokenP3 = 1000; +// tokenP4 = 2; +// methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8)"; +// hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP2, tokenP3, +// tokenP4)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 0); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// // validate assetissue precision can't more than 6 +// tokenP1 = "74657374"; +// tokenP2 = tokenP1; +// tokenP3 = 1000; +// tokenP4 = 7; +// methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8)"; +// hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP2, tokenP3, +// tokenP4)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 0); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// // trigger contract success +// tokenP1 = "74657374"; +// tokenP2 = tokenP1; +// tokenP3 = 1000; +// tokenP4 = 2; +// methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8)"; +// hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP2, tokenP3, +// tokenP4)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 1000001); +// long expectEnergyUsageTotal = 25000; +// long expectEnergyUsageTotalMax = 30000; +// long reallyEnergyUsageTotal = result.getReceipt().getEnergyUsageTotal(); +// // validate energy cost +// Assert.assertTrue(reallyEnergyUsageTotal > expectEnergyUsageTotal +// && reallyEnergyUsageTotal < expectEnergyUsageTotalMax); +// +// // validate assetissue An account can only issue one asset +// tokenP1 = "74657374"; +// tokenP2 = tokenP1; +// tokenP3 = 1000; +// tokenP4 = 2; +// methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8)"; +// hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP2, tokenP3, +// tokenP4)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 0); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// // Trigger contract method: UpdateAsset(trcToken, string, string) +// String methodUpdateAsset = "UpdateAsset(trcToken,string,string)"; +// // 1,abc,abc, +// long updateP1 = 1000001; +// String updateP2 = "abc"; +// String updateP3 = updateP2; +// hexInput = AbiUtil.parseMethod(methodUpdateAsset, Arrays.asList(updateP1, updateP2, updateP3)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() +// .get(0).getUrl().toByteArray()), "abc"); +// Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() +// .get(0).getDesc().toByteArray()), "abc"); +// // validate energy cost +// expectEnergyUsageTotal = 5000; +// expectEnergyUsageTotalMax = 10000; +// reallyEnergyUsageTotal = result.getReceipt().getEnergyUsageTotal(); +// +// Assert.assertTrue(reallyEnergyUsageTotal > expectEnergyUsageTotal +// && reallyEnergyUsageTotal < expectEnergyUsageTotalMax); +// +// // validate desc less than 200 +// updateP1 = 1000001; +// updateP2 = +// "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcab" +// + "cabcabcabcabcabcabcababcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcab" +// + "cabcabcabcabcabcabcabcabcabcabcabcabcabcababcabcabcabcabcabcabcabcabcabcabcabcab" +// + "cabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcababcabcabcabcabcab" +// + "cabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabca" +// + "bcab"; +// updateP3 = "efg"; +// hexInput = AbiUtil.parseMethod(methodUpdateAsset, Arrays.asList(updateP1, updateP2, updateP3)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() +// .get(0).getUrl().toByteArray()), "abc"); +// Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() +// .get(0).getDesc().toByteArray()), "abc"); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// // validate url less than 256 +// updateP1 = 1000001; +// updateP3 = +// "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcab" +// + "cabcabcabcabcabcabcaabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc" +// + "abcabcabcabcabcabcabcabcabcabcabcabcabcaabcabcabcabcabcabcabcabcabcabcabcabcabca" +// + "bcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcaabcabcabcabcabcabcab" +// + "cabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabca"; +// updateP2 = "efg"; +// hexInput = AbiUtil.parseMethod(methodUpdateAsset, Arrays.asList(updateP1, updateP2, updateP3)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// } +// +// /*pragma solidity ^0.5.12; +// contract HelloWorld{ +// function TokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) +// public { +// assetissue(name, abbr, totalSupply, precision); +// assetissue(name, abbr, totalSupply, precision); +// } +// function UpdateAsset(trcToken tokenId, string memory url, string memory desc) public { +// updateasset(tokenId, bytes(url), bytes(desc)); +// updateasset(tokenId, bytes(url), bytes(desc)); +// } +// }*/ +// +// @Test +// public void testTrc10ForMultiCall() throws ContractExeException, +// ReceiptCheckErrException, VMIllegalException, +// ContractValidateException { +// ConfigLoader.disable = true; +// VMConfig.initAllowTvmTransferTrc10(1); +// VMConfig.initAllowTvmConstantinople(1); +// VMConfig.initAllowTvmSolidity059(1); +// VMConfig.initAllowTvmAssetIssue(1); +// manager.getDynamicPropertiesStore().saveAllowSameTokenName(1); +// String contractName = "AssetIssueTest"; +// byte[] address = Hex.decode(OWNER_ADDRESS); +// String abi = "[{\"constant\":false,\"inputs\":[{\"internalType\":\"bytes32\"," +// + "\"name\":\"name\"," +// + "\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"abbr\"," +// + "\"type\":\"bytes32\"}," +// + "{\"internalType\":\"uint64\",\"name\":\"totalSupply\",\"type\":\"uint64\"}," +// + "{\"internalType\":\"uint8\",\"name\":\"precision\",\"type\":\"uint8\"}]," +// + "\"name\":\"TokenIssue\"," +// + "\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"function\"}," +// + "{\"constant\":false,\"inputs\":[{\"internalType\":\"trcToken\",\"name\":\"tokenId\"," +// + "\"type\":\"trcToken\"},{\"internalType\":\"string\",\"name\":\"desc\"," +// + "\"type\":\"string\"}," +// + "{\"internalType\":\"string\",\"name\":\"url\",\"type\":\"string\"}]," +// + "\"name\":\"UpdateAsset\"," +// + "\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"function\"}]"; +// String factoryCode = +// "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a576000" +// + "80fd5b506102858061003a6000396000f3fe608060405234801561001057600080fd5b50d3801561" +// + "001d57600080fd5b50d2801561002a57600080fd5b50600436106100505760003560e01c80633615" +// + "673e14610055578063f177bc7a146100ae575b600080fd5b6100ac6004803603608081101561006b" +// + "57600080fd5b810190808035906020019092919080359060200190929190803567ffffffffffffff" +// + "ff169060200190929190803560ff16906020019092919050505061020a565b005b61020860048036" +// + "0360608110156100c457600080fd5b81019080803590602001909291908035906020019064010000" +// + "00008111156100eb57600080fd5b8201836020820111156100fd57600080fd5b8035906020019184" +// + "600183028401116401000000008311171561011f57600080fd5b91908080601f0160208091040260" +// + "20016040519081016040528093929190818152602001838380828437600081840152601f19601f82" +// + "01169050808301925050505050505091929192908035906020019064010000000081111561018257" +// + "600080fd5b82018360208201111561019457600080fd5b8035906020019184600183028401116401" +// + "00000000831117156101b657600080fd5b91908080601f0160208091040260200160405190810160" +// + "40528093929190818152602001838380828437600081840152601f19601f82011690508083019250" +// + "505050505050919291929050505061021c565b005b80828486da5080828486da5050505050565b80" +// + "8284db50808284db5050505056fea26474726f6e582010b72c10cc2d93a0ddc6ec14e8a40345f73a" +// + "2263120bd04e1552687570eb950c64736f6c637828302e352e31332d646576656c6f702e32303230" +// + "2e382e31332b636f6d6d69742e37633236393863300057"; +// long value = 0; +// long fee = 100000000; +// long consumeUserResourcePercent = 0; +// // deploy contract +// Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, +// null); +// byte[] factoryAddress = WalletUtil.generateContractAddress(trx); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); +// Assert.assertNull(runtime.getRuntimeError()); +// +// // send coin +// rootRepository.addBalance(factoryAddress, 10000000000L); +// rootRepository.commit(); +// Assert.assertEquals(rootRepository.getBalance(factoryAddress), 10000000000L); +// +// // validate updateasset Asset is not existed in AssetIssueStore +// String methodUpdateAsset = "UpdateAsset(trcToken,string,string)"; +// // 1,abc,abc, +// long updateP1 = 1000001; +// String updateP2 = "616263"; +// String updateP3 = updateP2; +// String hexInput = AbiUtil.parseMethod(methodUpdateAsset, Arrays.asList(updateP1, updateP2, +// updateP3)); +// TVMTestResult result = +// TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// // multicall tokenissue +// String tokenP1 = "74657374"; +// long tokenP3 = 1000; +// long tokenP4 = 2; +// String methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8)"; +// hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP1, tokenP3, +// tokenP4)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 0); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// // multicall updateAsset +// methodUpdateAsset = "UpdateAsset(trcToken,string,string)"; +// // 1,abc,abc, +// updateP1 = 1000001; +// updateP2 = "abc"; +// updateP3 = updateP2; +// hexInput = AbiUtil.parseMethod(methodUpdateAsset, Arrays.asList(updateP1, updateP2, updateP3)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() +// .get(0).getUrl().toByteArray()), +// "abc"); +// Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() +// .get(0).getDesc().toByteArray()), +// "abc"); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// } +// +// /*pragma solidity ^0.5.12; +// contract HelloWorld{ +// function TokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision, +// address addr) public { +// address payable newaddress = address(uint160(addr)); +// newaddress.transfer(100000000); +// assetissue(name, abbr, totalSupply, precision); +// newaddress.transfer(100000000); +// } +// function UpdateAsset(trcToken tokenId, string memory url, string memory desc, address +// addr) public { +// address payable newaddress = address(uint160(addr)); +// newaddress.transfer(100000000); +// updateasset(tokenId, bytes(url), bytes(desc)); +// newaddress.transfer(100000000); +// } +// }*/ +// +// @Test +// public void testTrc10Exception() throws ContractExeException, +// ReceiptCheckErrException, VMIllegalException, +// ContractValidateException { +// ConfigLoader.disable = true; +// VMConfig.initAllowTvmTransferTrc10(1); +// VMConfig.initAllowTvmConstantinople(1); +// VMConfig.initAllowTvmSolidity059(1); +// VMConfig.initAllowTvmAssetIssue(1); +// String contractName = "AssetIssueTest"; +// byte[] address = Hex.decode(OWNER_ADDRESS); +// String abi = "[{\"constant\":false,\"inputs\":[{\"internalType\":\"bytes32\"," +// + "\"name\":\"name\"," +// + "\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"abbr\"," +// + "\"type\":\"bytes32\"}," +// + "{\"internalType\":\"uint64\",\"name\":\"totalSupply\",\"type\":\"uint64\"}," +// + "{\"internalType\":\"uint8\",\"name\":\"precision\",\"type\":\"uint8\"}," +// + "{\"internalType\":\"address\",\"name\":\"addr\",\"type\":\"address\"}]," +// + "\"name\":\"TokenIssue\"," +// + "\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"function\"}," +// + "{\"constant\":false,\"inputs\":[{\"internalType\":\"trcToken\",\"name\":\"tokenId\"," +// + "\"type\":\"trcToken\"},{\"internalType\":\"string\",\"name\":\"desc\"," +// + "\"type\":\"string\"}," +// + "{\"internalType\":\"string\",\"name\":\"url\",\"type\":\"string\"}," +// + "{\"internalType\":\"address\"," +// + "\"name\":\"addr\",\"type\":\"address\"}],\"name\":\"UpdateAsset\",\"outputs\":[]," +// + "\"payable\":false," +// + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"; +// String factoryCode = +// "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a576000" +// + "80fd5b506103f48061003a6000396000f3fe608060405234801561001057600080fd5b50d3801561" +// + "001d57600080fd5b50d2801561002a57600080fd5b50600436106100505760003560e01c8063451e" +// + "cfa214610055578063a241e431146100ce575b600080fd5b6100cc600480360360a081101561006b" +// + "57600080fd5b810190808035906020019092919080359060200190929190803567ffffffffffffff" +// + "ff169060200190929190803560ff169060200190929190803573ffffffffffffffffffffffffffff" +// + "ffffffffffff16906020019092919050505061024a565b005b610248600480360360808110156100" +// + "e457600080fd5b81019080803590602001909291908035906020019064010000000081111561010b" +// + "57600080fd5b82018360208201111561011d57600080fd5b80359060200191846001830284011164" +// + "01000000008311171561013f57600080fd5b91908080601f01602080910402602001604051908101" +// + "6040528093929190818152602001838380828437600081840152601f19601f820116905080830192" +// + "505050505050509192919290803590602001906401000000008111156101a257600080fd5b820183" +// + "6020820111156101b457600080fd5b80359060200191846001830284011164010000000083111715" +// + "6101d657600080fd5b91908080601f01602080910402602001604051908101604052809392919081" +// + "8152602001838380828437600081840152601f19601f820116905080830192505050505050509192" +// + "919290803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506102" +// + "f3565b005b60008190508073ffffffffffffffffffffffffffffffffffffffff166108fc6305f5e1" +// + "009081150290604051600060405180830381858888f19350505050158015610299573d6000803e3d" +// + "6000fd5b5082848688da508073ffffffffffffffffffffffffffffffffffffffff166108fc6305f5" +// + "e1009081150290604051600060405180830381858888f193505050501580156102ea573d6000803e" +// + "3d6000fd5b50505050505050565b60008190508073ffffffffffffffffffffffffffffffffffffff" +// + "ff166108fc6305f5e1009081150290604051600060405180830381858888f1935050505015801561" +// + "0342573d6000803e3d6000fd5b50828486db508073ffffffffffffffffffffffffffffffffffffff" +// + "ff166108fc6305f5e1009081150290604051600060405180830381858888f1935050505015801561" +// + "0392573d6000803e3d6000fd5b50505050505056fea26474726f6e5820e6e64fe3d21e1866d8b2da" +// + "9e9bba20e7b5fee47cf6122aae388eb63b4d3df07264736f6c637828302e352e31332d646576656c" +// + "6f702e323032302e382e31332b636f6d6d69742e37633236393863300057"; +// long value = 0; +// long fee = 100000000; +// long consumeUserResourcePercent = 0; +// // deploy contract +// Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, +// null); +// byte[] factoryAddress = WalletUtil.generateContractAddress(trx); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); +// Assert.assertNull(runtime.getRuntimeError()); +// +// // sendcoin to factoryAddress 100000000000 +// rootRepository.addBalance(factoryAddress, 10000000000L); +// rootRepository.commit(); +// Assert.assertEquals(rootRepository.getBalance(factoryAddress), 10000000000L); +// +// // assetissue exception test +// String tokenP1 = "74657374"; +// long tokenP3 = 1000; +// long tokenP4 = 7; +// String methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8,address)"; +// String receiveAddress = "27VZHn9PFZwNh7o2EporxmLkpe157iWZVkh"; +// String hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP1, +// tokenP3, tokenP4, receiveAddress)); +// TVMTestResult result = +// TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 0); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// Assert.assertEquals(200000000, +// rootRepository.getBalance(decode58Check(receiveAddress))); +// +// // updateasset exception test +// String methodUpdateAsset = "UpdateAsset(trcToken,string,string,address)"; +// // 1,abc,abc, +// long updateP1 = 1000001; +// String updateP2 = "616263"; +// hexInput = AbiUtil.parseMethod(methodUpdateAsset, Arrays.asList(updateP1, updateP2, updateP2, +// receiveAddress)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// Assert.assertEquals(200000000, rootRepository.getBalance(decode58Check(receiveAddress))); +// } +// +// /*pragma solidity ^0.5.0; +// contract A { +// function TokenIssueA(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) +// public returns (uint){ +// return assetissue(name, abbr, totalSupply, precision); +// } +// function UpdateAssetA(trcToken tokenId, string memory desc, string memory url) public { +// updateasset(tokenId, bytes(desc), bytes(url)); +// } +// } +// contract HelloWorld { +// A a = new A(); +// function TokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) +// public returns (uint) { +// return a.TokenIssueA(name, abbr, totalSupply, precision); +// } +// function UpdateAsset(trcToken tokenId, string memory url, string memory desc) public { +// a.UpdateAssetA(tokenId, url, desc); +// } +// function getContractAddress() public returns (address) { +// return address(a); +// } +// }*/ +// +// @Test +// public void testTrc10ContractCall() throws ContractExeException, +// ReceiptCheckErrException, VMIllegalException, +// ContractValidateException { +// ConfigLoader.disable = true; +// VMConfig.initAllowTvmTransferTrc10(1); +// VMConfig.initAllowTvmConstantinople(1); +// VMConfig.initAllowTvmSolidity059(1); +// VMConfig.initAllowTvmAssetIssue(1); +// manager.getDynamicPropertiesStore().saveAllowSameTokenName(1); +// String contractName = "AssetIssueTest"; +// byte[] address = Hex.decode(OWNER_ADDRESS); +// String abi = "[{\"constant\":false,\"inputs\":[{\"internalType\":\"bytes32\"," +// + "\"name\":\"name\"," +// + "\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"abbr\"," +// + "\"type\":\"bytes32\"}," +// + "{\"internalType\":\"uint64\",\"name\":\"totalSupply\",\"type\":\"uint64\"}," +// + "{\"internalType\":\"uint8\",\"name\":\"precision\",\"type\":\"uint8\"}]," +// + "\"name\":\"TokenIssue\"," +// + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}]," +// + "\"payable\":false," +// + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," +// + "\"inputs\":[{\"internalType\":\"trcToken\",\"name\":\"tokenId\",\"type\":\"trcToken\"}," +// + "{\"internalType\":\"string\",\"name\":\"desc\",\"type\":\"string\"}," +// + "{\"internalType\":\"string\"," +// + "\"name\":\"url\",\"type\":\"string\"}],\"name\":\"UpdateAsset\",\"outputs\":[]," +// + "\"payable\":false," +// + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," +// + "\"inputs\":[]," +// + "\"name\":\"getContractAddress\",\"outputs\":[{\"internalType\":\"address\"," +// + "\"name\":\"\"," +// + "\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"function\"}]"; +// String factoryCode = +// "608060405260405161001090610098565b604051809103906000f08015801561002c573d6000803e" +// + "3d6000fd5b506000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916" +// + "908373ffffffffffffffffffffffffffffffffffffffff16021790555034801561007857600080fd" +// + "5b50d3801561008557600080fd5b50d2801561009257600080fd5b506100a5565b6102cd80610602" +// + "83390190565b61054e806100b46000396000f3fe608060405234801561001057600080fd5b50d380" +// + "1561001d57600080fd5b50d2801561002a57600080fd5b506004361061005b5760003560e01c8063" +// + "32a2c5d0146100605780633615673e146100aa578063f177bc7a14610117575b600080fd5b610068" +// + "610273565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffff" +// + "ffffffffffffffffffffffffff16815260200191505060405180910390f35b610101600480360360" +// + "808110156100c057600080fd5b810190808035906020019092919080359060200190929190803567" +// + "ffffffffffffffff169060200190929190803560ff16906020019092919050505061029c565b6040" +// + "518082815260200191505060405180910390f35b6102716004803603606081101561012d57600080" +// + "fd5b81019080803590602001909291908035906020019064010000000081111561015457600080fd" +// + "5b82018360208201111561016657600080fd5b803590602001918460018302840111640100000000" +// + "8311171561018857600080fd5b91908080601f016020809104026020016040519081016040528093" +// + "929190818152602001838380828437600081840152601f19601f8201169050808301925050505050" +// + "50509192919290803590602001906401000000008111156101eb57600080fd5b8201836020820111" +// + "156101fd57600080fd5b8035906020019184600183028401116401000000008311171561021f5760" +// + "0080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001" +// + "838380828437600081840152601f19601f8201169050808301925050505050505091929192905050" +// + "50610389565b005b60008060009054906101000a900473ffffffffffffffffffffffffffffffffff" +// + "ffffff16905090565b60008060009054906101000a900473ffffffffffffffffffffffffffffffff" +// + "ffffffff1673ffffffffffffffffffffffffffffffffffffffff166329f00e598686868660405185" +// + "63ffffffff1660e01b8152600401808581526020018481526020018367ffffffffffffffff1667ff" +// + "ffffffffffffff1681526020018260ff1660ff168152602001945050505050602060405180830381" +// + "600087803b15801561034457600080fd5b505af1158015610358573d6000803e3d6000fd5b505050" +// + "506040513d602081101561036e57600080fd5b810190808051906020019092919050505090509493" +// + "50505050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff16" +// + "73ffffffffffffffffffffffffffffffffffffffff1663cfa62e758484846040518463ffffffff16" +// + "60e01b81526004018084815260200180602001806020018381038352858181518152602001915080" +// + "51906020019080838360005b83811015610422578082015181840152602081019050610407565b50" +// + "505050905090810190601f16801561044f5780820380516001836020036101000a03191681526020" +// + "0191505b50838103825284818151815260200191508051906020019080838360005b838110156104" +// + "8857808201518184015260208101905061046d565b50505050905090810190601f1680156104b557" +// + "80820380516001836020036101000a031916815260200191505b5095505050505050600060405180" +// + "830381600087803b1580156104d757600080fd5b505af11580156104eb573d6000803e3d6000fd5b" +// + "5050505050505056fea26474726f6e582068c6e59329c5b9e63f34ea5762d58db8649b294831356a" +// + "dfe323a04f3c96c25f64736f6c637828302e352e31332d646576656c6f702e323032302e382e3133" +// + "2b636f6d6d69742e37633236393863300057608060405234801561001057600080fd5b50d3801561" +// + "001d57600080fd5b50d2801561002a57600080fd5b506102938061003a6000396000f3fe60806040" +// + "5234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b50" +// + "600436106100505760003560e01c806329f00e5914610055578063cfa62e75146100c2575b600080" +// + "fd5b6100ac6004803603608081101561006b57600080fd5b81019080803590602001909291908035" +// + "9060200190929190803567ffffffffffffffff169060200190929190803560ff1690602001909291" +// + "9050505061021e565b6040518082815260200191505060405180910390f35b61021c600480360360" +// + "608110156100d857600080fd5b810190808035906020019092919080359060200190640100000000" +// + "8111156100ff57600080fd5b82018360208201111561011157600080fd5b80359060200191846001" +// + "83028401116401000000008311171561013357600080fd5b91908080601f01602080910402602001" +// + "6040519081016040528093929190818152602001838380828437600081840152601f19601f820116" +// + "90508083019250505050505050919291929080359060200190640100000000811115610196576000" +// + "80fd5b8201836020820111156101a857600080fd5b80359060200191846001830284011164010000" +// + "0000831117156101ca57600080fd5b91908080601f01602080910402602001604051908101604052" +// + "8093929190818152602001838380828437600081840152601f19601f820116905080830192505050" +// + "50505050919291929050505061022f565b005b600081838587da9050949350505050565b808284db" +// + "5050505056fea26474726f6e582071af66a376cfd560797ad3c889d08b9037d8ec121805b96fd252" +// + "3415b77f4df264736f6c637828302e352e31332d646576656c6f702e323032302e382e31332b636f" +// + "6d6d69742e37633236393863300057"; +// long value = 0; +// long fee = 100000000; +// long consumeUserResourcePercent = 0; +// // deploy contract +// Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, +// null); +// byte[] factoryAddress = WalletUtil.generateContractAddress(trx); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); +// Assert.assertNull(runtime.getRuntimeError()); +// +// // Trigger contract method: getContractAddress() +// String methodByAddr = "getContractAddress()"; +// String hexInput = AbiUtil.parseMethod(methodByAddr, Collections.emptyList()); +// TVMTestResult result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// byte[] returnValue = result.getRuntime().getResult().getHReturn(); +// +// // Contract A Address +// String tmpAddress = "a0" + Hex.toHexString(returnValue).substring(24); +// +// // sendcoin to A address 100000000000 +// rootRepository.addBalance(ByteArray.fromHexString(tmpAddress), 10000000000L); +// rootRepository.commit(); +// Assert.assertEquals(rootRepository.getBalance(ByteArray.fromHexString(tmpAddress)), +// 10000000000L); +// +// // assetissue test +// String tokenP1 = "74657374"; +// long tokenP3 = 1000; +// long tokenP4 = 2; +// String methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8)"; +// hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP1, tokenP3, +// tokenP4)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 1000001); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// // updateasset test +// String methodUpdateAsset = "UpdateAsset(trcToken,string,string)"; +// // 1,abc,abc, +// long updateP1 = 1000001; +// String updateP2 = "abc"; +// hexInput = AbiUtil.parseMethod(methodUpdateAsset, Arrays.asList(updateP1, updateP2, updateP2)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() +// .get(0).getUrl().toByteArray()), +// "abc"); +// Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() +// .get(0).getDesc().toByteArray()), +// "abc"); +// } +//} +// +// +// diff --git a/framework/src/test/java/org/tron/common/runtime/vm/UnStakeTest.java b/framework/src/test/java/org/tron/common/runtime/vm/UnStakeTest.java index 37a680d93fe..e115486370b 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/UnStakeTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/UnStakeTest.java @@ -1,129 +1,129 @@ -package org.tron.common.runtime.vm; - -import java.util.Arrays; -import java.util.Collections; -import lombok.extern.slf4j.Slf4j; -import org.junit.Test; -import org.spongycastle.util.encoders.Hex; -import org.testng.Assert; -import org.tron.common.runtime.TVMTestResult; -import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.utils.WalletUtil; -import org.tron.core.exception.ContractExeException; -import org.tron.core.exception.ContractValidateException; -import org.tron.core.exception.ReceiptCheckErrException; -import org.tron.core.exception.VMIllegalException; -import org.tron.core.vm.config.ConfigLoader; -import org.tron.core.vm.config.VMConfig; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.utils.AbiUtil; - -@Slf4j -public class UnStakeTest extends VMContractTestBase { - - /*pragma solidity ^0.5.0; - contract HelloWorld{ - function stakeTest(address sr, uint256 amount) public returns (bool) { - return stake(sr, amount); - } - function unstakeTest() public public returns (bool) { - return unstake(); - } - function withdrawRewardTest() public returns (uint) { - return withdrawreward(); - } - function rewardBalanceTest(address addr) public returns (uint) { - return addr.rewardbalance; - } - }*/ - - @Test - public void testUnstake() throws ContractExeException, - ReceiptCheckErrException, VMIllegalException, - ContractValidateException { - ConfigLoader.disable = true; - VMConfig.initAllowTvmTransferTrc10(1); - VMConfig.initAllowTvmConstantinople(1); - VMConfig.initAllowTvmSolidity059(1); - VMConfig.initAllowTvmStake(1); - manager.getDynamicPropertiesStore().saveChangeDelegation(1); - String contractName = "unstakeTest"; - byte[] address = Hex.decode(OWNER_ADDRESS); - String abi = "[{\"constant\":false,\"inputs\":[{\"internalType\":\"address\"," - + "\"name\":\"addr\"," - + "\"type\":\"address\"}],\"name\":\"rewardBalanceTest\"," - + "\"outputs\":[{\"internalType\":\"uint256\"," - + "\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false," - + "\"stateMutability\":\"nonpayable\"," - + "\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"address\"," - + "\"name\":\"sr\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\"," - + "\"type\":\"uint256\"}],\"name\":\"stakeTest\",\"outputs\":[{\"internalType\":\"bool\"," - + "\"name\":\"\"," - + "\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," - + "\"type\":\"function\"}," - + "{\"constant\":false,\"inputs\":[],\"name\":\"unstakeTest\"," - + "\"outputs\":[{\"internalType\":\"bool\"," - + "\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," - + "\"type\":\"function\"},{\"constant\":false,\"inputs\":[]," - + "\"name\":\"withdrawRewardTest\"," - + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}]," - + "\"payable\":false," - + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"; - String factoryCode = - "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a576000" - + "80fd5b506102018061003a6000396000f3fe608060405234801561001057600080fd5b50d3801561" - + "001d57600080fd5b50d2801561002a57600080fd5b50600436106100665760003560e01c8063a223" - + "c65f1461006b578063b3e835e1146100c3578063c290120a146100e5578063e49de2d01461010357" - + "5b600080fd5b6100ad6004803603602081101561008157600080fd5b81019080803573ffffffffff" - + "ffffffffffffffffffffffffffffff169060200190929190505050610169565b6040518082815260" - + "200191505060405180910390f35b6100cb61018a565b604051808215151515815260200191505060" - + "405180910390f35b6100ed610192565b6040518082815260200191505060405180910390f35b6101" - + "4f6004803603604081101561011957600080fd5b81019080803573ffffffffffffffffffffffffff" - + "ffffffffffffff1690602001909291908035906020019092919050505061019a565b604051808215" - + "151515815260200191505060405180910390f35b60008173ffffffffffffffffffffffffffffffff" - + "ffffffff16d89050919050565b6000d6905090565b6000d7905090565b60008183d5905092915050" - + "56fea26474726f6e58204ba2e62e49bd76cb49dd0e1ce7be45dcae5f764ea02b1a11a34c7ef83ca3" - + "362764736f6c637828302e352e31332d646576656c6f702e323032302e382e31332b636f6d6d6974" - + "2e37633236393863300057"; - long value = 0; - long fee = 100000000; - long consumeUserResourcePercent = 0; - // deploy contract - Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, - null); - byte[] factoryAddress = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); - Assert.assertNull(runtime.getRuntimeError()); - - rootRepository.addBalance(factoryAddress, 10000000000L); - rootRepository.commit(); - Assert.assertEquals(rootRepository.getBalance(factoryAddress), 10000000000L); - - manager.getDynamicPropertiesStore().saveMinFrozenTime(0); - - // Trigger contract method: stakeTest(address,uint256) - String stakeTest = "stakeTest(address,uint256)"; - String witness = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; - String hexInput = AbiUtil.parseMethod(stakeTest, Arrays.asList(witness, 100000000)); - TVMTestResult result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - byte[] returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000001"); - - //vote - String unstakeTest = "unstakeTest()"; - hexInput = AbiUtil.parseMethod(unstakeTest, Collections.emptyList()); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000001"); - } - -} +//package org.tron.common.runtime.vm; +// +//import java.util.Arrays; +//import java.util.Collections; +//import lombok.extern.slf4j.Slf4j; +//import org.junit.Test; +//import org.spongycastle.util.encoders.Hex; +//import org.testng.Assert; +//import org.tron.common.runtime.TVMTestResult; +//import org.tron.common.runtime.TvmTestUtils; +//import org.tron.common.utils.WalletUtil; +//import org.tron.core.exception.ContractExeException; +//import org.tron.core.exception.ContractValidateException; +//import org.tron.core.exception.ReceiptCheckErrException; +//import org.tron.core.exception.VMIllegalException; +//import org.tron.core.vm.config.ConfigLoader; +//import org.tron.core.vm.config.VMConfig; +//import org.tron.protos.Protocol; +//import stest.tron.wallet.common.client.utils.AbiUtil; +// +//@Slf4j +//public class UnStakeTest extends VMContractTestBase { +// +// /*pragma solidity ^0.5.0; +// contract HelloWorld{ +// function stakeTest(address sr, uint256 amount) public returns (bool) { +// return stake(sr, amount); +// } +// function unstakeTest() public public returns (bool) { +// return unstake(); +// } +// function withdrawRewardTest() public returns (uint) { +// return withdrawreward(); +// } +// function rewardBalanceTest(address addr) public returns (uint) { +// return addr.rewardbalance; +// } +// }*/ +// +// @Test +// public void testUnstake() throws ContractExeException, +// ReceiptCheckErrException, VMIllegalException, +// ContractValidateException { +// ConfigLoader.disable = true; +// VMConfig.initAllowTvmTransferTrc10(1); +// VMConfig.initAllowTvmConstantinople(1); +// VMConfig.initAllowTvmSolidity059(1); +// VMConfig.initAllowTvmStake(1); +// manager.getDynamicPropertiesStore().saveChangeDelegation(1); +// String contractName = "unstakeTest"; +// byte[] address = Hex.decode(OWNER_ADDRESS); +// String abi = "[{\"constant\":false,\"inputs\":[{\"internalType\":\"address\"," +// + "\"name\":\"addr\"," +// + "\"type\":\"address\"}],\"name\":\"rewardBalanceTest\"," +// + "\"outputs\":[{\"internalType\":\"uint256\"," +// + "\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false," +// + "\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"address\"," +// + "\"name\":\"sr\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\"," +// + "\"type\":\"uint256\"}],\"name\":\"stakeTest\",\"outputs\":[{\"internalType\":\"bool\"," +// + "\"name\":\"\"," +// + "\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"function\"}," +// + "{\"constant\":false,\"inputs\":[],\"name\":\"unstakeTest\"," +// + "\"outputs\":[{\"internalType\":\"bool\"," +// + "\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"function\"},{\"constant\":false,\"inputs\":[]," +// + "\"name\":\"withdrawRewardTest\"," +// + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}]," +// + "\"payable\":false," +// + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"; +// String factoryCode = +// "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a576000" +// + "80fd5b506102018061003a6000396000f3fe608060405234801561001057600080fd5b50d3801561" +// + "001d57600080fd5b50d2801561002a57600080fd5b50600436106100665760003560e01c8063a223" +// + "c65f1461006b578063b3e835e1146100c3578063c290120a146100e5578063e49de2d01461010357" +// + "5b600080fd5b6100ad6004803603602081101561008157600080fd5b81019080803573ffffffffff" +// + "ffffffffffffffffffffffffffffff169060200190929190505050610169565b6040518082815260" +// + "200191505060405180910390f35b6100cb61018a565b604051808215151515815260200191505060" +// + "405180910390f35b6100ed610192565b6040518082815260200191505060405180910390f35b6101" +// + "4f6004803603604081101561011957600080fd5b81019080803573ffffffffffffffffffffffffff" +// + "ffffffffffffff1690602001909291908035906020019092919050505061019a565b604051808215" +// + "151515815260200191505060405180910390f35b60008173ffffffffffffffffffffffffffffffff" +// + "ffffffff16d89050919050565b6000d6905090565b6000d7905090565b60008183d5905092915050" +// + "56fea26474726f6e58204ba2e62e49bd76cb49dd0e1ce7be45dcae5f764ea02b1a11a34c7ef83ca3" +// + "362764736f6c637828302e352e31332d646576656c6f702e323032302e382e31332b636f6d6d6974" +// + "2e37633236393863300057"; +// long value = 0; +// long fee = 100000000; +// long consumeUserResourcePercent = 0; +// // deploy contract +// Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, +// null); +// byte[] factoryAddress = WalletUtil.generateContractAddress(trx); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); +// Assert.assertNull(runtime.getRuntimeError()); +// +// rootRepository.addBalance(factoryAddress, 10000000000L); +// rootRepository.commit(); +// Assert.assertEquals(rootRepository.getBalance(factoryAddress), 10000000000L); +// +// manager.getDynamicPropertiesStore().saveMinFrozenTime(0); +// +// // Trigger contract method: stakeTest(address,uint256) +// String stakeTest = "stakeTest(address,uint256)"; +// String witness = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; +// String hexInput = AbiUtil.parseMethod(stakeTest, Arrays.asList(witness, 100000000)); +// TVMTestResult result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// byte[] returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000001"); +// +// //vote +// String unstakeTest = "unstakeTest()"; +// hexInput = AbiUtil.parseMethod(unstakeTest, Collections.emptyList()); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000001"); +// } +// +//} diff --git a/framework/src/test/java/org/tron/common/runtime/vm/WithdrawRewardTest.java b/framework/src/test/java/org/tron/common/runtime/vm/WithdrawRewardTest.java index 1c783d27e8e..a7b8455c166 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/WithdrawRewardTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/WithdrawRewardTest.java @@ -1,956 +1,956 @@ -package org.tron.common.runtime.vm; - -import com.google.protobuf.ByteString; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.Collections; -import java.util.Map; - -import lombok.extern.slf4j.Slf4j; -import org.junit.Test; -import org.spongycastle.util.encoders.Hex; -import org.testng.Assert; -import org.tron.common.crypto.ECKey; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.runtime.TVMTestResult; -import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Sha256Hash; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.WalletUtil; -import org.tron.consensus.base.Param; -import org.tron.core.capsule.BlockCapsule; -import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.exception.AccountResourceInsufficientException; -import org.tron.core.exception.BadBlockException; -import org.tron.core.exception.BadNumberBlockException; -import org.tron.core.exception.ContractExeException; -import org.tron.core.exception.ContractValidateException; -import org.tron.core.exception.DupTransactionException; -import org.tron.core.exception.NonCommonBlockException; -import org.tron.core.exception.ReceiptCheckErrException; -import org.tron.core.exception.TaposException; -import org.tron.core.exception.TooBigTransactionException; -import org.tron.core.exception.TooBigTransactionResultException; -import org.tron.core.exception.TransactionExpirationException; -import org.tron.core.exception.UnLinkedBlockException; -import org.tron.core.exception.VMIllegalException; -import org.tron.core.exception.ValidateScheduleException; -import org.tron.core.exception.ValidateSignatureException; -import org.tron.core.exception.ZksnarkException; -import org.tron.core.vm.config.ConfigLoader; -import org.tron.core.vm.config.VMConfig; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.utils.AbiUtil; - -@Slf4j -public class WithdrawRewardTest extends VMContractTestBase { - - /* - pragma solidity ^0.5.0; - - contract ContractB{ - address user; - - constructor() payable public { - user = msg.sender; - } - - function stakeTest(address sr, uint256 amount) public returns (bool) { - return stake(sr, amount); - } - - function withdrawRewardTest() public returns (uint) { - return withdrawreward(); - } - } - - contract TestRewardBalance{ - address user; - - ContractB contractB = new ContractB(); - - constructor() payable public { - user = msg.sender; - } - - function stakeTest(address sr, uint256 amount) public returns (bool) { - return stake(sr, amount); - } - - function unstakeTest() public { - unstake(); - } - - function contractBStakeTest(address sr, uint256 amount) public returns (bool) { - return contractB.stakeTest(sr, amount); - } - - function withdrawRewardTest() public returns (uint) { - return withdrawreward(); - } - - function rewardBalanceTest(address addr) public returns (uint) { - return addr.rewardbalance; - } - - function localContractAddrTest() view public returns (uint256) { - address payable localContract = address(uint160(address(this))); - return localContract.rewardbalance; - } - - function otherContractAddrTest() view public returns (uint256) { - address payable localContract = address(uint160(address(contractB))); - return localContract.rewardbalance; - } - - function contractBWithdrawRewardTest() public returns (uint) { - return contractB.withdrawRewardTest(); - } - - function getContractBAddressTest() public returns (address) { - return address(contractB); - } - } - */ - - public String getABI() { - String abi = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\"," - + "\"type\":\"constructor\"},{\"constant\":false," - + "\"inputs\":[{\"internalType\":\"address\",\"name\":\"sr\"," - + "\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\"," - + "\"type\":\"uint256\"}],\"name\":\"contractBStakeTest\"," - + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," - + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," - + "{\"constant\":false,\"inputs\":[],\"name\":\"contractBWithdrawRewardTest\"," - + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," - + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," - + "\"type\":\"function\"},{\"constant\":false,\"inputs\":[]," - + "\"name\":\"getContractBAddressTest\"," - + "\"outputs\":[{\"internalType\":\"address\",\"name\":\"\"," - + "\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," - + "\"type\":\"function\"},{\"constant\":false,\"inputs\":[]," - + "\"name\":\"localContractAddrTest\",\"outputs\":[{\"internalType\":\"uint256\"," - + "\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false," - + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," - + "\"inputs\":[],\"name\":\"otherContractAddrTest\"," - + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," - + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," - + "\"type\":\"function\"},{\"constant\":false," - + "\"inputs\":[{\"internalType\":\"address\",\"name\":\"addr\"," - + "\"type\":\"address\"}],\"name\":\"rewardBalanceTest\"," - + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," - + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," - + "\"type\":\"function\"},{\"constant\":false," - + "\"inputs\":[{\"internalType\":\"address\",\"name\":\"sr\"," - + "\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\"," - + "\"type\":\"uint256\"}],\"name\":\"stakeTest\"," - + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," - + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," - + "{\"constant\":false,\"inputs\":[],\"name\":\"unstakeTest\",\"outputs\":[]," - + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," - + "{\"constant\":false,\"inputs\":[],\"name\":\"withdrawRewardTest\"," - + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," - + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," - + "\"type\":\"function\"}]"; - - return abi; - } - - public String getFactoryCode() { - String factoryCode = "60806040526040516100109061005c565b604051809103906" - + "000f08015801561002c573d6000803e3d6000fd5b50600180546001600160a" - + "01b03929092166001600160a01b03199283161790556000805490911633179" - + "055610069565b6101108061039c83390190565b61032480610078600039600" - + "0f3fe608060405234801561001057600080fd5b50d3801561001d57600080f" - + "d5b50d2801561002a57600080fd5b50600436106100ad5760003560e01c806" - + "3b3e835e111610080578063b3e835e114610156578063c290120a146101605" - + "78063cb2d51cf14610168578063d30a28ee14610170578063e49de2d014610" - + "178576100ad565b806310198157146100b257806325a26c30146100d657806" - + "38db848f114610116578063a223c65f14610130575b600080fd5b6100ba610" - + "1a4565b604080516001600160a01b039092168252519081900360200190f35" - + "b610102600480360360408110156100ec57600080fd5b506001600160a01b0" - + "381351690602001356101b3565b60408051911515825251908190036020019" - + "0f35b61011e61023f565b60408051918252519081900360200190f35b61011" - + "e6004803603602081101561014657600080fd5b50356001600160a01b03166" - + "102b6565b61015e6102c3565b005b61011e6102c7565b61011e6102cf565b6" - + "1011e6102d4565b6101026004803603604081101561018e57600080fd5b506" - + "001600160a01b0381351690602001356102e4565b6001546001600160a01b0" - + "31690565b60015460408051630e49de2d60e41b81526001600160a01b03858" - + "1166004830152602482018590529151600093929092169163e49de2d091604" - + "48082019260209290919082900301818787803b15801561020c57600080fd5" - + "b505af1158015610220573d6000803e3d6000fd5b505050506040513d60208" - + "1101561023657600080fd5b50519392505050565b600154604080516361480" - + "90560e11b815290516000926001600160a01b03169163c290120a916004808" - + "30192602092919082900301818787803b15801561028557600080fd5b505af" - + "1158015610299573d6000803e3d6000fd5b505050506040513d60208110156" - + "102af57600080fd5b5051905090565b6001600160a01b0316d890565bd6505" - + "65b6000d7905090565b30d890565b6001546001600160a01b0316d890565b6" - + "0008183d5939250505056fea26474726f6e582064d946716e1b0c5f00dcf70" - + "b3ff065ea0587cd3719b2ba94783edeb58413020464736f6c634300050d003" - + "16080604052600080546001600160a01b0319163317905560ec80610024600" - + "0396000f3fe6080604052348015600f57600080fd5b50d38015601b5760008" - + "0fd5b50d28015602757600080fd5b5060043610604a5760003560e01c8063c" - + "290120a14604f578063e49de2d0146067575b600080fd5b605560a4565b604" - + "08051918252519081900360200190f35b609060048036036040811015607b5" - + "7600080fd5b506001600160a01b03813516906020013560ac565b604080519" - + "115158252519081900360200190f35b6000d7905090565b60008183d593925" - + "0505056fea26474726f6e5820f52f0d803d46c1926596c7faa3b969812b567" - + "66163eb8ca0270d34e3cff1d3b164736f6c634300050d0031"; - - return factoryCode; - } - - @Test - public void testWithdrawRewardInLocalContract() - throws ContractExeException, ReceiptCheckErrException, ValidateSignatureException, - BadNumberBlockException, ValidateScheduleException, ContractValidateException, - VMIllegalException, DupTransactionException, TooBigTransactionException, - TooBigTransactionResultException, BadBlockException, NonCommonBlockException, - TransactionExpirationException, UnLinkedBlockException, TaposException, - ZksnarkException, AccountResourceInsufficientException { - ConfigLoader.disable = true; - VMConfig.initAllowTvmTransferTrc10(1); - VMConfig.initAllowTvmConstantinople(1); - VMConfig.initAllowTvmSolidity059(1); - VMConfig.initAllowTvmStake(1); - manager.getDynamicPropertiesStore().saveChangeDelegation(1); - - String contractName = "TestWithdrawReward"; - byte[] address = Hex.decode(OWNER_ADDRESS); - String abi = getABI(); - String factoryCode = getFactoryCode(); - - long value = 1000000000; - long fee = 100000000; - long consumeUserResourcePercent = 0; - - // deploy contract - Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, - null); - byte[] factoryAddress = WalletUtil.generateContractAddress(trx); - String factoryAddressStr = StringUtil.encode58Check(factoryAddress); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); - Assert.assertNull(runtime.getRuntimeError()); - - // Trigger contract method: stakeTest(address,uint256) - String methodByAddr = "stakeTest(address,uint256)"; - String witness = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; - String hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList(witness, 100000000)); - TVMTestResult result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - byte[] returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000001"); - - // Do Maintenance & Generate New Block - maintenanceManager.doMaintenance(); - String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; - byte[] privateKey = ByteArray.fromHexString(key); - final ECKey ecKey = ECKey.fromPrivate(privateKey); - byte[] witnessAddress = ecKey.getAddress(); - WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(witnessAddress)); - chainBaseManager.addWitness(ByteString.copyFrom(witnessAddress)); - Protocol.Block block = getSignedBlock(witnessCapsule.getAddress(), 1533529947843L, privateKey); - manager.pushBlock(new BlockCapsule(block));//cycle: 1 addReward - - // Trigger contract method: rewardBalanceTest(address) - methodByAddr = "rewardBalanceTest(address)"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // Trigger contract method: localContractAddrTest() - methodByAddr = "localContractAddrTest()"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - Protocol.Block newBlock = getBlock(witnessCapsule.getAddress(), - System.currentTimeMillis(), privateKey); - BlockCapsule blockCapsule = new BlockCapsule(newBlock); - blockCapsule.generatedByMyself = true; - - // Trigger contract method: withdrawRewardTest() - methodByAddr = "withdrawRewardTest()"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // Execute Next Cycle - maintenanceManager.doMaintenance(); - WitnessCapsule localWitnessCapsule = manager.getWitnessStore() - .get(StringUtil.hexString2ByteString(WITNESS_SR1_ADDRESS).toByteArray()); - Assert.assertEquals(205, localWitnessCapsule.getVoteCount()); - - // Trigger contract method: rewardBalanceTest(address) - methodByAddr = "rewardBalanceTest(address)"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - BigInteger reward = new BigInteger(Hex.toHexString(returnValue), 16); - - // Current Reward: Total Reward * Vote Rate - // BigInteger reward = new BigInteger(Hex.toHexString(returnValue), 16); - // byte[] sr1 = decodeFromBase58Check(witness); - // long totalReward = (long) ((double) rootRepository - // .getDelegationStore().getReward(1, sr1)); - // long totalVote = rootRepository.getDelegationStore().getWitnessVote(1, sr1); - // double voteRate = (double) 100 / totalVote; - // long curReward = (long) (totalReward * voteRate); - // Assert.assertEquals(reward.longValue(), curReward); - - //total reward: block reward + vote reward - long blockReward = 25600000; - long voteReward = 2186667; - long totalReward = blockReward + voteReward; - double voteRate = (double) 100 / 205; - long curReward = (long) (totalReward * voteRate); - Assert.assertEquals(reward.longValue(), curReward); - - // Trigger contract method: localContractAddrTest() - methodByAddr = "localContractAddrTest()"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - - Assert.assertEquals((new BigInteger(Hex.toHexString(returnValue), 16)).longValue(), curReward); - - // Trigger contract method: withdrawRewardTest() - methodByAddr = "withdrawRewardTest()"; - - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - - Assert.assertEquals((new BigInteger(Hex.toHexString(returnValue), 16)).longValue(), curReward); - - // Trigger contract method: rewardBalanceTest(address) - methodByAddr = "rewardBalanceTest(address)"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // Trigger contract method: localContractAddrTest() - methodByAddr = "localContractAddrTest()"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // Trigger contract method: withdrawRewardTest() - methodByAddr = "withdrawRewardTest()"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - ConfigLoader.disable = false; - } - - @Test - public void testWithdrawRewardInAnotherContract() - throws ContractExeException, ReceiptCheckErrException, VMIllegalException, - ContractValidateException, DupTransactionException, TooBigTransactionException, - AccountResourceInsufficientException, BadBlockException, NonCommonBlockException, - TransactionExpirationException, UnLinkedBlockException, ZksnarkException, - TaposException, TooBigTransactionResultException, ValidateSignatureException, - BadNumberBlockException, ValidateScheduleException { - ConfigLoader.disable = true; - VMConfig.initAllowTvmTransferTrc10(1); - VMConfig.initAllowTvmConstantinople(1); - VMConfig.initAllowTvmSolidity059(1); - VMConfig.initAllowTvmStake(1); - manager.getDynamicPropertiesStore().saveChangeDelegation(1); - - String contractName = "TestWithdrawRewardWithContract"; - byte[] address = Hex.decode(OWNER_ADDRESS); - String abi = getABI(); - String factoryCode = getFactoryCode(); - long value = 1000000000; - long fee = 100000000; - long consumeUserResourcePercent = 0; - - // deploy contract - 27kR8yXGYQykQ2fgH3h9sqfNBSeEh23ggja - Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, - null); - byte[] factoryAddress = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); - Assert.assertNull(runtime.getRuntimeError()); - - // Trigger contract method: getContractBAddressTest() - String methodByAddr = "getContractBAddressTest()"; - String hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - TVMTestResult result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - byte[] returnValue = result.getRuntime().getResult().getHReturn(); - - // Contract B Address: 27Wvtyhk4hHqRzogLPSJ21TjDdpuTJZWvQD" - String tmpAddress = "a0" + Hex.toHexString(returnValue).substring(24); - String contractBAddress = StringUtil.encode58Check(ByteArray.fromHexString(tmpAddress)); - rootRepository.addBalance(Hex.decode(tmpAddress), 30000000000000L); - rootRepository.commit(); - - // Trigger contract method: contractBStakeTest(address,uint256) - methodByAddr = "contractBStakeTest(address,uint256)"; - String witness = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; - hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList(witness, 200000000)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000001"); - - // Do Maintenance & Generate New Block - maintenanceManager.doMaintenance(); - String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; - byte[] privateKey = ByteArray.fromHexString(key); - final ECKey ecKey = ECKey.fromPrivate(privateKey); - byte[] witnessAddress = ecKey.getAddress(); - WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(witnessAddress)); - chainBaseManager.addWitness(ByteString.copyFrom(witnessAddress)); - Protocol.Block block = getSignedBlock(witnessCapsule.getAddress(), 1533529947843L, privateKey); - manager.pushBlock(new BlockCapsule(block));//cycle: 1 addReward - - // Trigger contract method: rewardBalanceTest(address) - methodByAddr = "rewardBalanceTest(address)"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(contractBAddress)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // Trigger contract method: otherContractAddrTest() - methodByAddr = "otherContractAddrTest()"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // Trigger contract method: contractBWithdrawRewardTest() - Protocol.Block newBlock = getBlock(witnessCapsule.getAddress(), - System.currentTimeMillis(), privateKey); - BlockCapsule blockCapsule = new BlockCapsule(newBlock); - blockCapsule.generatedByMyself = true; - - methodByAddr = "contractBWithdrawRewardTest()"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // Execute Next Cycle - maintenanceManager.doMaintenance(); - WitnessCapsule localWitnessCapsule = manager.getWitnessStore() - .get(StringUtil.hexString2ByteString(WITNESS_SR1_ADDRESS).toByteArray()); - Assert.assertEquals(localWitnessCapsule.getVoteCount(), 305); - - // Trigger contract method: rewardBalanceTest(address) - methodByAddr = "rewardBalanceTest(address)"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(contractBAddress)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - BigInteger reward = new BigInteger(Hex.toHexString(returnValue), 16); - - // Current Reward: Total Reward * Vote Rate - // byte[] sr1 = decodeFromBase58Check(witness); - // long totalReward = (long) ((double) rootRepository - // .getDelegationStore().getReward(1, sr1)); - // long totalVote = rootRepository.getDelegationStore().getWitnessVote(1, sr1); - // double voteRate = (double) 200 / totalVote; - // long curReward = (long) (totalReward * voteRate); - // Assert.assertEquals(curReward, reward.longValue()); - - //total reward: block reward + vote reward - long blockReward = 25600000; - long voteReward = 3003077; - long totalReward = blockReward + voteReward; - double voteRate = (double) 200 / 305; - long curReward = (long) (totalReward * voteRate); - Assert.assertEquals(reward.longValue(), curReward); - - // Trigger contract method: otherContractAddrTest() - methodByAddr = "otherContractAddrTest()"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - - Assert.assertEquals((new BigInteger(Hex.toHexString(returnValue), 16)).longValue(), curReward); - - // Trigger contract method: contractBWithdrawRewardTest() - methodByAddr = "contractBWithdrawRewardTest()"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - - Assert.assertEquals((new BigInteger(Hex.toHexString(returnValue), 16)).longValue(), curReward); - - // Trigger contract method: rewardBalanceTest(address) - methodByAddr = "rewardBalanceTest(address)"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(contractBAddress)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // Trigger contract method: otherContractAddrTest() - methodByAddr = "otherContractAddrTest()"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // Trigger contract method: contractBWithdrawRewardTest() - methodByAddr = "contractBWithdrawRewardTest()"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - ConfigLoader.disable = false; - } - - public Protocol.Block getSignedBlock(ByteString witness, long time, byte[] privateKey) { - long blockTime = System.currentTimeMillis() / 3000 * 3000; - if (time != 0) { - blockTime = time; - } else { - if (chainBaseManager.getHeadBlockId().getNum() != 0) { - blockTime = chainBaseManager.getHeadBlockTimeStamp() + 3000; - } - } - Param param = Param.getInstance(); - Param.Miner miner = param.new Miner(privateKey, witness, witness); - BlockCapsule blockCapsule = manager - .generateBlock(miner, time, System.currentTimeMillis() + 1000); - Protocol.Block block = blockCapsule.getInstance(); - - Protocol.BlockHeader.raw raw = block.getBlockHeader().getRawData().toBuilder() - .setParentHash(ByteString - .copyFrom(chainBaseManager.getDynamicPropertiesStore() - .getLatestBlockHeaderHash().getBytes())) - .setNumber(chainBaseManager.getDynamicPropertiesStore() - .getLatestBlockHeaderNumber() + 1) - .setTimestamp(blockTime) - .setWitnessAddress(witness) - .build(); - - ECKey ecKey = ECKey.fromPrivate(privateKey); - ECKey.ECDSASignature signature = ecKey.sign(Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), raw.toByteArray()).getBytes()); - ByteString sign = ByteString.copyFrom(signature.toByteArray()); - - Protocol.BlockHeader blockHeader = block.getBlockHeader().toBuilder() - .setRawData(raw) - .setWitnessSignature(sign) - .build(); - - Protocol.Block signedBlock = block.toBuilder().setBlockHeader(blockHeader).build(); - - return signedBlock; - } - - public Protocol.Block getBlock(ByteString witness, long time, byte[] privateKey) { - long blockTime = System.currentTimeMillis() / 3000 * 3000; - if (time != 0) { - blockTime = time; - } else { - if (chainBaseManager.getHeadBlockId().getNum() != 0) { - blockTime = chainBaseManager.getHeadBlockTimeStamp() + 3000; - } - } - Param param = Param.getInstance(); - Param.Miner miner = param.new Miner(privateKey, witness, witness); - BlockCapsule blockCapsule = manager - .generateBlock(miner, time, System.currentTimeMillis() + 1000); - Protocol.Block block = blockCapsule.getInstance(); - Protocol.BlockHeader.raw raw = block.getBlockHeader().getRawData().toBuilder() - .setParentHash(ByteString - .copyFrom(chainBaseManager.getDynamicPropertiesStore() - .getLatestBlockHeaderHash().getBytes())) - .setNumber(chainBaseManager.getDynamicPropertiesStore() - .getLatestBlockHeaderNumber() + 1) - .setTimestamp(blockTime) - .setWitnessAddress(witness) - .build(); - ECKey ecKey = ECKey.fromPrivate(privateKey); - ECKey.ECDSASignature signature = ecKey.sign(Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), raw.toByteArray()).getBytes()); - // ByteString sign = ByteString.copyFrom(signature.toByteArray()); - Protocol.BlockHeader blockHeader = block.getBlockHeader().toBuilder() - .setRawData(raw) - .setWitnessSignature(ByteString.copyFromUtf8("")) - .build(); - Protocol.Block signedBlock = block.toBuilder().setBlockHeader(blockHeader).build(); - return signedBlock; - } - - @Test - public void testWithdrawRewardInLocalContractAfter24Hour() - throws ContractExeException, ReceiptCheckErrException, ValidateSignatureException, - BadNumberBlockException, ValidateScheduleException, ContractValidateException, - VMIllegalException, DupTransactionException, TooBigTransactionException, - TooBigTransactionResultException, BadBlockException, NonCommonBlockException, - TransactionExpirationException, UnLinkedBlockException, TaposException, - ZksnarkException, AccountResourceInsufficientException { - ConfigLoader.disable = true; - VMConfig.initAllowTvmTransferTrc10(1); - VMConfig.initAllowTvmConstantinople(1); - VMConfig.initAllowTvmSolidity059(1); - VMConfig.initAllowTvmStake(1); - manager.getDynamicPropertiesStore().saveChangeDelegation(1); - - String contractName = "TestWithdrawReward"; - byte[] address = Hex.decode(OWNER_ADDRESS); - String abi = getABI(); - String factoryCode = getFactoryCode(); - long value = 1000000000; - long fee = 100000000; - long consumeUserResourcePercent = 0; - - // deploy contract - Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, - null); - byte[] factoryAddress = WalletUtil.generateContractAddress(trx); - String factoryAddressStr = StringUtil.encode58Check(factoryAddress); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); - Assert.assertNull(runtime.getRuntimeError()); - - // Trigger contract method: stakeTest(address,uint256) - String methodByAddr = "stakeTest(address,uint256)"; - String witness = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; - String hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList(witness, 100000000)); - TVMTestResult result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - byte[] returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000001"); - - // Do Maintenance & Generate New Block - maintenanceManager.doMaintenance(); - String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; - byte[] privateKey = ByteArray.fromHexString(key); - final ECKey ecKey = ECKey.fromPrivate(privateKey); - byte[] witnessAddress = ecKey.getAddress(); - WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(witnessAddress)); - chainBaseManager.addWitness(ByteString.copyFrom(witnessAddress)); - Protocol.Block block = getSignedBlock(witnessCapsule.getAddress(), - System.currentTimeMillis(), privateKey); - manager.pushBlock(new BlockCapsule(block));//cycle: 1 addReward - - // Trigger contract method: rewardBalanceTest(address) - methodByAddr = "rewardBalanceTest(address)"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - Protocol.Block newBlock = getBlock(witnessCapsule.getAddress(), - System.currentTimeMillis(), privateKey); - BlockCapsule blockCapsule = new BlockCapsule(newBlock); - blockCapsule.generatedByMyself = true; - - // Trigger contract method: withdrawRewardTest() - methodByAddr = "withdrawRewardTest()"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // Execute Next Cycle - maintenanceManager.doMaintenance(); - WitnessCapsule localWitnessCapsule = manager.getWitnessStore() - .get(StringUtil.hexString2ByteString(WITNESS_SR1_ADDRESS).toByteArray()); - Assert.assertEquals(205, localWitnessCapsule.getVoteCount()); - - // Trigger contract method: rewardBalanceTest(address) - methodByAddr = "rewardBalanceTest(address)"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - BigInteger reward = new BigInteger(Hex.toHexString(returnValue), 16); - - // Current Reward: Total Reward * Vote Rate - // BigInteger reward = new BigInteger(Hex.toHexString(returnValue), 16); - // byte[] sr1 = decodeFromBase58Check(witness); - // long totalReward = (long) ((double) rootRepository - // .getDelegationStore().getReward(1, sr1)); - // long totalVote = rootRepository.getDelegationStore().getWitnessVote(1, sr1); - // double voteRate = (double) 100 / totalVote; - // long curReward = (long) (totalReward * voteRate); - // Assert.assertEquals(reward.longValue(), curReward); - - //total reward: block reward + vote reward - long blockReward = 25600000; - long voteReward = 2186667; - long totalReward = blockReward + voteReward; - double voteRate = (double) 100 / 205; - long curReward = (long) (totalReward * voteRate); - Assert.assertEquals(reward.longValue(), curReward); - - // Trigger contract method: localContractAddrTest() - methodByAddr = "localContractAddrTest()"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - - Assert.assertEquals((new BigInteger(Hex.toHexString(returnValue), 16)).longValue(), curReward); - - // Trigger contract method: withdrawRewardTest() - methodByAddr = "withdrawRewardTest()"; - - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - - Assert.assertEquals((new BigInteger(Hex.toHexString(returnValue), 16)).longValue(), curReward); - - // Trigger contract method: rewardBalanceTest(address) - methodByAddr = "rewardBalanceTest(address)"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // Trigger contract method: withdrawRewardTest() - methodByAddr = "withdrawRewardTest()"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // Within 24 Hours - long num = chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber(); - ByteString latestHeadHash = - chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderHash().getByteString(); - blockCapsule = - createTestBlockCapsule( - System.currentTimeMillis() + 80400000, - num + 1, - latestHeadHash); - manager.pushBlock(blockCapsule); - - // long currentTime = System.currentTimeMillis(); - // for (int i = 0; i < (86400 / 3 - 3); i++) { - // currentTime += 3000; - // ByteString latestHeadHash = chainBaseManager.getDynamicPropertiesStore() - // .getLatestBlockHeaderHash().getByteString(); - // blockCapsule = - // createTestBlockCapsule( - // currentTime, - // ++num, - // latestHeadHash, - // privateKey); - // manager.pushBlock(blockCapsule); - // } - - // Trigger contract method: withdrawRewardTest() - methodByAddr = "withdrawRewardTest()"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - // After 24 Hours - num = chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber(); - latestHeadHash = - chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderHash().getByteString(); - blockCapsule = - createTestBlockCapsule( - System.currentTimeMillis() + 86400000 + 3000, - num + 1, - latestHeadHash); - manager.pushBlock(blockCapsule); - // for (int i = 0; i < 3; i++) { - // currentTime += 3000; - // ByteString latestHeadHash = chainBaseManager.getDynamicPropertiesStore() - // .getLatestBlockHeaderHash().getByteString(); - // blockCapsule = - // createTestBlockCapsule( - // currentTime, - // ++num, - // latestHeadHash, - // privateKey); - // manager.pushBlock(blockCapsule); - // } - - // Trigger contract method: withdrawRewardTest() - methodByAddr = "withdrawRewardTest()"; - hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - returnValue = result.getRuntime().getResult().getHReturn(); - Assert.assertNotEquals(Hex.toHexString(returnValue), - "0000000000000000000000000000000000000000000000000000000000000000"); - - ConfigLoader.disable = false; - } - - private BlockCapsule createTestBlockCapsule(long time, - long number, ByteString hash) { - ByteString witnessAddress = dposSlot.getScheduledWitness(dposSlot.getSlot(time)); - BlockCapsule blockCapsule = new BlockCapsule(number, Sha256Hash.wrap(hash), time, - witnessAddress); - blockCapsule.generatedByMyself = true; - blockCapsule.setMerkleRoot(); - //blockCapsule.sign(privateKey); - //blockCapsule.sign(ByteArray.fromHexString(privateKey.get(witnessAddress))); - return blockCapsule; - } -} - - +//package org.tron.common.runtime.vm; +// +//import com.google.protobuf.ByteString; +//import java.math.BigInteger; +//import java.util.Arrays; +//import java.util.Collections; +//import java.util.Map; +// +//import lombok.extern.slf4j.Slf4j; +//import org.junit.Test; +//import org.spongycastle.util.encoders.Hex; +//import org.testng.Assert; +//import org.tron.common.crypto.ECKey; +//import org.tron.common.parameter.CommonParameter; +//import org.tron.common.runtime.TVMTestResult; +//import org.tron.common.runtime.TvmTestUtils; +//import org.tron.common.utils.ByteArray; +//import org.tron.common.utils.Sha256Hash; +//import org.tron.common.utils.StringUtil; +//import org.tron.common.utils.WalletUtil; +//import org.tron.consensus.base.Param; +//import org.tron.core.capsule.BlockCapsule; +//import org.tron.core.capsule.WitnessCapsule; +//import org.tron.core.exception.AccountResourceInsufficientException; +//import org.tron.core.exception.BadBlockException; +//import org.tron.core.exception.BadNumberBlockException; +//import org.tron.core.exception.ContractExeException; +//import org.tron.core.exception.ContractValidateException; +//import org.tron.core.exception.DupTransactionException; +//import org.tron.core.exception.NonCommonBlockException; +//import org.tron.core.exception.ReceiptCheckErrException; +//import org.tron.core.exception.TaposException; +//import org.tron.core.exception.TooBigTransactionException; +//import org.tron.core.exception.TooBigTransactionResultException; +//import org.tron.core.exception.TransactionExpirationException; +//import org.tron.core.exception.UnLinkedBlockException; +//import org.tron.core.exception.VMIllegalException; +//import org.tron.core.exception.ValidateScheduleException; +//import org.tron.core.exception.ValidateSignatureException; +//import org.tron.core.exception.ZksnarkException; +//import org.tron.core.vm.config.ConfigLoader; +//import org.tron.core.vm.config.VMConfig; +//import org.tron.protos.Protocol; +//import org.tron.protos.Protocol.Transaction; +//import stest.tron.wallet.common.client.utils.AbiUtil; +// +//@Slf4j +//public class WithdrawRewardTest extends VMContractTestBase { +// +// /* +// pragma solidity ^0.5.0; +// +// contract ContractB{ +// address user; +// +// constructor() payable public { +// user = msg.sender; +// } +// +// function stakeTest(address sr, uint256 amount) public returns (bool) { +// return stake(sr, amount); +// } +// +// function withdrawRewardTest() public returns (uint) { +// return withdrawreward(); +// } +// } +// +// contract TestRewardBalance{ +// address user; +// +// ContractB contractB = new ContractB(); +// +// constructor() payable public { +// user = msg.sender; +// } +// +// function stakeTest(address sr, uint256 amount) public returns (bool) { +// return stake(sr, amount); +// } +// +// function unstakeTest() public { +// unstake(); +// } +// +// function contractBStakeTest(address sr, uint256 amount) public returns (bool) { +// return contractB.stakeTest(sr, amount); +// } +// +// function withdrawRewardTest() public returns (uint) { +// return withdrawreward(); +// } +// +// function rewardBalanceTest(address addr) public returns (uint) { +// return addr.rewardbalance; +// } +// +// function localContractAddrTest() view public returns (uint256) { +// address payable localContract = address(uint160(address(this))); +// return localContract.rewardbalance; +// } +// +// function otherContractAddrTest() view public returns (uint256) { +// address payable localContract = address(uint160(address(contractB))); +// return localContract.rewardbalance; +// } +// +// function contractBWithdrawRewardTest() public returns (uint) { +// return contractB.withdrawRewardTest(); +// } +// +// function getContractBAddressTest() public returns (address) { +// return address(contractB); +// } +// } +// */ +// +// public String getABI() { +// String abi = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\"," +// + "\"type\":\"constructor\"},{\"constant\":false," +// + "\"inputs\":[{\"internalType\":\"address\",\"name\":\"sr\"," +// + "\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\"," +// + "\"type\":\"uint256\"}],\"name\":\"contractBStakeTest\"," +// + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," +// + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," +// + "{\"constant\":false,\"inputs\":[],\"name\":\"contractBWithdrawRewardTest\"," +// + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," +// + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"function\"},{\"constant\":false,\"inputs\":[]," +// + "\"name\":\"getContractBAddressTest\"," +// + "\"outputs\":[{\"internalType\":\"address\",\"name\":\"\"," +// + "\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"function\"},{\"constant\":false,\"inputs\":[]," +// + "\"name\":\"localContractAddrTest\",\"outputs\":[{\"internalType\":\"uint256\"," +// + "\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false," +// + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," +// + "\"inputs\":[],\"name\":\"otherContractAddrTest\"," +// + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," +// + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"function\"},{\"constant\":false," +// + "\"inputs\":[{\"internalType\":\"address\",\"name\":\"addr\"," +// + "\"type\":\"address\"}],\"name\":\"rewardBalanceTest\"," +// + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," +// + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"function\"},{\"constant\":false," +// + "\"inputs\":[{\"internalType\":\"address\",\"name\":\"sr\"," +// + "\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\"," +// + "\"type\":\"uint256\"}],\"name\":\"stakeTest\"," +// + "\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}]," +// + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," +// + "{\"constant\":false,\"inputs\":[],\"name\":\"unstakeTest\",\"outputs\":[]," +// + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," +// + "{\"constant\":false,\"inputs\":[],\"name\":\"withdrawRewardTest\"," +// + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," +// + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"function\"}]"; +// +// return abi; +// } +// +// public String getFactoryCode() { +// String factoryCode = "60806040526040516100109061005c565b604051809103906" +// + "000f08015801561002c573d6000803e3d6000fd5b50600180546001600160a" +// + "01b03929092166001600160a01b03199283161790556000805490911633179" +// + "055610069565b6101108061039c83390190565b61032480610078600039600" +// + "0f3fe608060405234801561001057600080fd5b50d3801561001d57600080f" +// + "d5b50d2801561002a57600080fd5b50600436106100ad5760003560e01c806" +// + "3b3e835e111610080578063b3e835e114610156578063c290120a146101605" +// + "78063cb2d51cf14610168578063d30a28ee14610170578063e49de2d014610" +// + "178576100ad565b806310198157146100b257806325a26c30146100d657806" +// + "38db848f114610116578063a223c65f14610130575b600080fd5b6100ba610" +// + "1a4565b604080516001600160a01b039092168252519081900360200190f35" +// + "b610102600480360360408110156100ec57600080fd5b506001600160a01b0" +// + "381351690602001356101b3565b60408051911515825251908190036020019" +// + "0f35b61011e61023f565b60408051918252519081900360200190f35b61011" +// + "e6004803603602081101561014657600080fd5b50356001600160a01b03166" +// + "102b6565b61015e6102c3565b005b61011e6102c7565b61011e6102cf565b6" +// + "1011e6102d4565b6101026004803603604081101561018e57600080fd5b506" +// + "001600160a01b0381351690602001356102e4565b6001546001600160a01b0" +// + "31690565b60015460408051630e49de2d60e41b81526001600160a01b03858" +// + "1166004830152602482018590529151600093929092169163e49de2d091604" +// + "48082019260209290919082900301818787803b15801561020c57600080fd5" +// + "b505af1158015610220573d6000803e3d6000fd5b505050506040513d60208" +// + "1101561023657600080fd5b50519392505050565b600154604080516361480" +// + "90560e11b815290516000926001600160a01b03169163c290120a916004808" +// + "30192602092919082900301818787803b15801561028557600080fd5b505af" +// + "1158015610299573d6000803e3d6000fd5b505050506040513d60208110156" +// + "102af57600080fd5b5051905090565b6001600160a01b0316d890565bd6505" +// + "65b6000d7905090565b30d890565b6001546001600160a01b0316d890565b6" +// + "0008183d5939250505056fea26474726f6e582064d946716e1b0c5f00dcf70" +// + "b3ff065ea0587cd3719b2ba94783edeb58413020464736f6c634300050d003" +// + "16080604052600080546001600160a01b0319163317905560ec80610024600" +// + "0396000f3fe6080604052348015600f57600080fd5b50d38015601b5760008" +// + "0fd5b50d28015602757600080fd5b5060043610604a5760003560e01c8063c" +// + "290120a14604f578063e49de2d0146067575b600080fd5b605560a4565b604" +// + "08051918252519081900360200190f35b609060048036036040811015607b5" +// + "7600080fd5b506001600160a01b03813516906020013560ac565b604080519" +// + "115158252519081900360200190f35b6000d7905090565b60008183d593925" +// + "0505056fea26474726f6e5820f52f0d803d46c1926596c7faa3b969812b567" +// + "66163eb8ca0270d34e3cff1d3b164736f6c634300050d0031"; +// +// return factoryCode; +// } +// +// @Test +// public void testWithdrawRewardInLocalContract() +// throws ContractExeException, ReceiptCheckErrException, ValidateSignatureException, +// BadNumberBlockException, ValidateScheduleException, ContractValidateException, +// VMIllegalException, DupTransactionException, TooBigTransactionException, +// TooBigTransactionResultException, BadBlockException, NonCommonBlockException, +// TransactionExpirationException, UnLinkedBlockException, TaposException, +// ZksnarkException, AccountResourceInsufficientException { +// ConfigLoader.disable = true; +// VMConfig.initAllowTvmTransferTrc10(1); +// VMConfig.initAllowTvmConstantinople(1); +// VMConfig.initAllowTvmSolidity059(1); +// VMConfig.initAllowTvmStake(1); +// manager.getDynamicPropertiesStore().saveChangeDelegation(1); +// +// String contractName = "TestWithdrawReward"; +// byte[] address = Hex.decode(OWNER_ADDRESS); +// String abi = getABI(); +// String factoryCode = getFactoryCode(); +// +// long value = 1000000000; +// long fee = 100000000; +// long consumeUserResourcePercent = 0; +// +// // deploy contract +// Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, +// null); +// byte[] factoryAddress = WalletUtil.generateContractAddress(trx); +// String factoryAddressStr = StringUtil.encode58Check(factoryAddress); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); +// Assert.assertNull(runtime.getRuntimeError()); +// +// // Trigger contract method: stakeTest(address,uint256) +// String methodByAddr = "stakeTest(address,uint256)"; +// String witness = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; +// String hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList(witness, 100000000)); +// TVMTestResult result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// byte[] returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000001"); +// +// // Do Maintenance & Generate New Block +// maintenanceManager.doMaintenance(); +// String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; +// byte[] privateKey = ByteArray.fromHexString(key); +// final ECKey ecKey = ECKey.fromPrivate(privateKey); +// byte[] witnessAddress = ecKey.getAddress(); +// WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(witnessAddress)); +// chainBaseManager.addWitness(ByteString.copyFrom(witnessAddress)); +// Protocol.Block block = getSignedBlock(witnessCapsule.getAddress(), 1533529947843L, privateKey); +// manager.pushBlock(new BlockCapsule(block));//cycle: 1 addReward +// +// // Trigger contract method: rewardBalanceTest(address) +// methodByAddr = "rewardBalanceTest(address)"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // Trigger contract method: localContractAddrTest() +// methodByAddr = "localContractAddrTest()"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// Protocol.Block newBlock = getBlock(witnessCapsule.getAddress(), +// System.currentTimeMillis(), privateKey); +// BlockCapsule blockCapsule = new BlockCapsule(newBlock); +// blockCapsule.generatedByMyself = true; +// +// // Trigger contract method: withdrawRewardTest() +// methodByAddr = "withdrawRewardTest()"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // Execute Next Cycle +// maintenanceManager.doMaintenance(); +// WitnessCapsule localWitnessCapsule = manager.getWitnessStore() +// .get(StringUtil.hexString2ByteString(WITNESS_SR1_ADDRESS).toByteArray()); +// Assert.assertEquals(205, localWitnessCapsule.getVoteCount()); +// +// // Trigger contract method: rewardBalanceTest(address) +// methodByAddr = "rewardBalanceTest(address)"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// BigInteger reward = new BigInteger(Hex.toHexString(returnValue), 16); +// +// // Current Reward: Total Reward * Vote Rate +// // BigInteger reward = new BigInteger(Hex.toHexString(returnValue), 16); +// // byte[] sr1 = decodeFromBase58Check(witness); +// // long totalReward = (long) ((double) rootRepository +// // .getDelegationStore().getReward(1, sr1)); +// // long totalVote = rootRepository.getDelegationStore().getWitnessVote(1, sr1); +// // double voteRate = (double) 100 / totalVote; +// // long curReward = (long) (totalReward * voteRate); +// // Assert.assertEquals(reward.longValue(), curReward); +// +// //total reward: block reward + vote reward +// long blockReward = 25600000; +// long voteReward = 2186667; +// long totalReward = blockReward + voteReward; +// double voteRate = (double) 100 / 205; +// long curReward = (long) (totalReward * voteRate); +// Assert.assertEquals(reward.longValue(), curReward); +// +// // Trigger contract method: localContractAddrTest() +// methodByAddr = "localContractAddrTest()"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// +// Assert.assertEquals((new BigInteger(Hex.toHexString(returnValue), 16)).longValue(), curReward); +// +// // Trigger contract method: withdrawRewardTest() +// methodByAddr = "withdrawRewardTest()"; +// +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// +// Assert.assertEquals((new BigInteger(Hex.toHexString(returnValue), 16)).longValue(), curReward); +// +// // Trigger contract method: rewardBalanceTest(address) +// methodByAddr = "rewardBalanceTest(address)"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // Trigger contract method: localContractAddrTest() +// methodByAddr = "localContractAddrTest()"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // Trigger contract method: withdrawRewardTest() +// methodByAddr = "withdrawRewardTest()"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// ConfigLoader.disable = false; +// } +// +// @Test +// public void testWithdrawRewardInAnotherContract() +// throws ContractExeException, ReceiptCheckErrException, VMIllegalException, +// ContractValidateException, DupTransactionException, TooBigTransactionException, +// AccountResourceInsufficientException, BadBlockException, NonCommonBlockException, +// TransactionExpirationException, UnLinkedBlockException, ZksnarkException, +// TaposException, TooBigTransactionResultException, ValidateSignatureException, +// BadNumberBlockException, ValidateScheduleException { +// ConfigLoader.disable = true; +// VMConfig.initAllowTvmTransferTrc10(1); +// VMConfig.initAllowTvmConstantinople(1); +// VMConfig.initAllowTvmSolidity059(1); +// VMConfig.initAllowTvmStake(1); +// manager.getDynamicPropertiesStore().saveChangeDelegation(1); +// +// String contractName = "TestWithdrawRewardWithContract"; +// byte[] address = Hex.decode(OWNER_ADDRESS); +// String abi = getABI(); +// String factoryCode = getFactoryCode(); +// long value = 1000000000; +// long fee = 100000000; +// long consumeUserResourcePercent = 0; +// +// // deploy contract - 27kR8yXGYQykQ2fgH3h9sqfNBSeEh23ggja +// Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, +// null); +// byte[] factoryAddress = WalletUtil.generateContractAddress(trx); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); +// Assert.assertNull(runtime.getRuntimeError()); +// +// // Trigger contract method: getContractBAddressTest() +// String methodByAddr = "getContractBAddressTest()"; +// String hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// TVMTestResult result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// byte[] returnValue = result.getRuntime().getResult().getHReturn(); +// +// // Contract B Address: 27Wvtyhk4hHqRzogLPSJ21TjDdpuTJZWvQD" +// String tmpAddress = "a0" + Hex.toHexString(returnValue).substring(24); +// String contractBAddress = StringUtil.encode58Check(ByteArray.fromHexString(tmpAddress)); +// rootRepository.addBalance(Hex.decode(tmpAddress), 30000000000000L); +// rootRepository.commit(); +// +// // Trigger contract method: contractBStakeTest(address,uint256) +// methodByAddr = "contractBStakeTest(address,uint256)"; +// String witness = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList(witness, 200000000)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000001"); +// +// // Do Maintenance & Generate New Block +// maintenanceManager.doMaintenance(); +// String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; +// byte[] privateKey = ByteArray.fromHexString(key); +// final ECKey ecKey = ECKey.fromPrivate(privateKey); +// byte[] witnessAddress = ecKey.getAddress(); +// WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(witnessAddress)); +// chainBaseManager.addWitness(ByteString.copyFrom(witnessAddress)); +// Protocol.Block block = getSignedBlock(witnessCapsule.getAddress(), 1533529947843L, privateKey); +// manager.pushBlock(new BlockCapsule(block));//cycle: 1 addReward +// +// // Trigger contract method: rewardBalanceTest(address) +// methodByAddr = "rewardBalanceTest(address)"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(contractBAddress)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // Trigger contract method: otherContractAddrTest() +// methodByAddr = "otherContractAddrTest()"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // Trigger contract method: contractBWithdrawRewardTest() +// Protocol.Block newBlock = getBlock(witnessCapsule.getAddress(), +// System.currentTimeMillis(), privateKey); +// BlockCapsule blockCapsule = new BlockCapsule(newBlock); +// blockCapsule.generatedByMyself = true; +// +// methodByAddr = "contractBWithdrawRewardTest()"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // Execute Next Cycle +// maintenanceManager.doMaintenance(); +// WitnessCapsule localWitnessCapsule = manager.getWitnessStore() +// .get(StringUtil.hexString2ByteString(WITNESS_SR1_ADDRESS).toByteArray()); +// Assert.assertEquals(localWitnessCapsule.getVoteCount(), 305); +// +// // Trigger contract method: rewardBalanceTest(address) +// methodByAddr = "rewardBalanceTest(address)"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(contractBAddress)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// BigInteger reward = new BigInteger(Hex.toHexString(returnValue), 16); +// +// // Current Reward: Total Reward * Vote Rate +// // byte[] sr1 = decodeFromBase58Check(witness); +// // long totalReward = (long) ((double) rootRepository +// // .getDelegationStore().getReward(1, sr1)); +// // long totalVote = rootRepository.getDelegationStore().getWitnessVote(1, sr1); +// // double voteRate = (double) 200 / totalVote; +// // long curReward = (long) (totalReward * voteRate); +// // Assert.assertEquals(curReward, reward.longValue()); +// +// //total reward: block reward + vote reward +// long blockReward = 25600000; +// long voteReward = 3003077; +// long totalReward = blockReward + voteReward; +// double voteRate = (double) 200 / 305; +// long curReward = (long) (totalReward * voteRate); +// Assert.assertEquals(reward.longValue(), curReward); +// +// // Trigger contract method: otherContractAddrTest() +// methodByAddr = "otherContractAddrTest()"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// +// Assert.assertEquals((new BigInteger(Hex.toHexString(returnValue), 16)).longValue(), curReward); +// +// // Trigger contract method: contractBWithdrawRewardTest() +// methodByAddr = "contractBWithdrawRewardTest()"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// +// Assert.assertEquals((new BigInteger(Hex.toHexString(returnValue), 16)).longValue(), curReward); +// +// // Trigger contract method: rewardBalanceTest(address) +// methodByAddr = "rewardBalanceTest(address)"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(contractBAddress)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // Trigger contract method: otherContractAddrTest() +// methodByAddr = "otherContractAddrTest()"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // Trigger contract method: contractBWithdrawRewardTest() +// methodByAddr = "contractBWithdrawRewardTest()"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// ConfigLoader.disable = false; +// } +// +// public Protocol.Block getSignedBlock(ByteString witness, long time, byte[] privateKey) { +// long blockTime = System.currentTimeMillis() / 3000 * 3000; +// if (time != 0) { +// blockTime = time; +// } else { +// if (chainBaseManager.getHeadBlockId().getNum() != 0) { +// blockTime = chainBaseManager.getHeadBlockTimeStamp() + 3000; +// } +// } +// Param param = Param.getInstance(); +// Param.Miner miner = param.new Miner(privateKey, witness, witness); +// BlockCapsule blockCapsule = manager +// .generateBlock(miner, time, System.currentTimeMillis() + 1000); +// Protocol.Block block = blockCapsule.getInstance(); +// +// Protocol.BlockHeader.raw raw = block.getBlockHeader().getRawData().toBuilder() +// .setParentHash(ByteString +// .copyFrom(chainBaseManager.getDynamicPropertiesStore() +// .getLatestBlockHeaderHash().getBytes())) +// .setNumber(chainBaseManager.getDynamicPropertiesStore() +// .getLatestBlockHeaderNumber() + 1) +// .setTimestamp(blockTime) +// .setWitnessAddress(witness) +// .build(); +// +// ECKey ecKey = ECKey.fromPrivate(privateKey); +// ECKey.ECDSASignature signature = ecKey.sign(Sha256Hash.of(CommonParameter +// .getInstance().isECKeyCryptoEngine(), raw.toByteArray()).getBytes()); +// ByteString sign = ByteString.copyFrom(signature.toByteArray()); +// +// Protocol.BlockHeader blockHeader = block.getBlockHeader().toBuilder() +// .setRawData(raw) +// .setWitnessSignature(sign) +// .build(); +// +// Protocol.Block signedBlock = block.toBuilder().setBlockHeader(blockHeader).build(); +// +// return signedBlock; +// } +// +// public Protocol.Block getBlock(ByteString witness, long time, byte[] privateKey) { +// long blockTime = System.currentTimeMillis() / 3000 * 3000; +// if (time != 0) { +// blockTime = time; +// } else { +// if (chainBaseManager.getHeadBlockId().getNum() != 0) { +// blockTime = chainBaseManager.getHeadBlockTimeStamp() + 3000; +// } +// } +// Param param = Param.getInstance(); +// Param.Miner miner = param.new Miner(privateKey, witness, witness); +// BlockCapsule blockCapsule = manager +// .generateBlock(miner, time, System.currentTimeMillis() + 1000); +// Protocol.Block block = blockCapsule.getInstance(); +// Protocol.BlockHeader.raw raw = block.getBlockHeader().getRawData().toBuilder() +// .setParentHash(ByteString +// .copyFrom(chainBaseManager.getDynamicPropertiesStore() +// .getLatestBlockHeaderHash().getBytes())) +// .setNumber(chainBaseManager.getDynamicPropertiesStore() +// .getLatestBlockHeaderNumber() + 1) +// .setTimestamp(blockTime) +// .setWitnessAddress(witness) +// .build(); +// ECKey ecKey = ECKey.fromPrivate(privateKey); +// ECKey.ECDSASignature signature = ecKey.sign(Sha256Hash.of(CommonParameter +// .getInstance().isECKeyCryptoEngine(), raw.toByteArray()).getBytes()); +// // ByteString sign = ByteString.copyFrom(signature.toByteArray()); +// Protocol.BlockHeader blockHeader = block.getBlockHeader().toBuilder() +// .setRawData(raw) +// .setWitnessSignature(ByteString.copyFromUtf8("")) +// .build(); +// Protocol.Block signedBlock = block.toBuilder().setBlockHeader(blockHeader).build(); +// return signedBlock; +// } +// +// @Test +// public void testWithdrawRewardInLocalContractAfter24Hour() +// throws ContractExeException, ReceiptCheckErrException, ValidateSignatureException, +// BadNumberBlockException, ValidateScheduleException, ContractValidateException, +// VMIllegalException, DupTransactionException, TooBigTransactionException, +// TooBigTransactionResultException, BadBlockException, NonCommonBlockException, +// TransactionExpirationException, UnLinkedBlockException, TaposException, +// ZksnarkException, AccountResourceInsufficientException { +// ConfigLoader.disable = true; +// VMConfig.initAllowTvmTransferTrc10(1); +// VMConfig.initAllowTvmConstantinople(1); +// VMConfig.initAllowTvmSolidity059(1); +// VMConfig.initAllowTvmStake(1); +// manager.getDynamicPropertiesStore().saveChangeDelegation(1); +// +// String contractName = "TestWithdrawReward"; +// byte[] address = Hex.decode(OWNER_ADDRESS); +// String abi = getABI(); +// String factoryCode = getFactoryCode(); +// long value = 1000000000; +// long fee = 100000000; +// long consumeUserResourcePercent = 0; +// +// // deploy contract +// Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, +// null); +// byte[] factoryAddress = WalletUtil.generateContractAddress(trx); +// String factoryAddressStr = StringUtil.encode58Check(factoryAddress); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); +// Assert.assertNull(runtime.getRuntimeError()); +// +// // Trigger contract method: stakeTest(address,uint256) +// String methodByAddr = "stakeTest(address,uint256)"; +// String witness = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; +// String hexInput = AbiUtil.parseMethod(methodByAddr, Arrays.asList(witness, 100000000)); +// TVMTestResult result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// byte[] returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000001"); +// +// // Do Maintenance & Generate New Block +// maintenanceManager.doMaintenance(); +// String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; +// byte[] privateKey = ByteArray.fromHexString(key); +// final ECKey ecKey = ECKey.fromPrivate(privateKey); +// byte[] witnessAddress = ecKey.getAddress(); +// WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(witnessAddress)); +// chainBaseManager.addWitness(ByteString.copyFrom(witnessAddress)); +// Protocol.Block block = getSignedBlock(witnessCapsule.getAddress(), +// System.currentTimeMillis(), privateKey); +// manager.pushBlock(new BlockCapsule(block));//cycle: 1 addReward +// +// // Trigger contract method: rewardBalanceTest(address) +// methodByAddr = "rewardBalanceTest(address)"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// Protocol.Block newBlock = getBlock(witnessCapsule.getAddress(), +// System.currentTimeMillis(), privateKey); +// BlockCapsule blockCapsule = new BlockCapsule(newBlock); +// blockCapsule.generatedByMyself = true; +// +// // Trigger contract method: withdrawRewardTest() +// methodByAddr = "withdrawRewardTest()"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // Execute Next Cycle +// maintenanceManager.doMaintenance(); +// WitnessCapsule localWitnessCapsule = manager.getWitnessStore() +// .get(StringUtil.hexString2ByteString(WITNESS_SR1_ADDRESS).toByteArray()); +// Assert.assertEquals(205, localWitnessCapsule.getVoteCount()); +// +// // Trigger contract method: rewardBalanceTest(address) +// methodByAddr = "rewardBalanceTest(address)"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// BigInteger reward = new BigInteger(Hex.toHexString(returnValue), 16); +// +// // Current Reward: Total Reward * Vote Rate +// // BigInteger reward = new BigInteger(Hex.toHexString(returnValue), 16); +// // byte[] sr1 = decodeFromBase58Check(witness); +// // long totalReward = (long) ((double) rootRepository +// // .getDelegationStore().getReward(1, sr1)); +// // long totalVote = rootRepository.getDelegationStore().getWitnessVote(1, sr1); +// // double voteRate = (double) 100 / totalVote; +// // long curReward = (long) (totalReward * voteRate); +// // Assert.assertEquals(reward.longValue(), curReward); +// +// //total reward: block reward + vote reward +// long blockReward = 25600000; +// long voteReward = 2186667; +// long totalReward = blockReward + voteReward; +// double voteRate = (double) 100 / 205; +// long curReward = (long) (totalReward * voteRate); +// Assert.assertEquals(reward.longValue(), curReward); +// +// // Trigger contract method: localContractAddrTest() +// methodByAddr = "localContractAddrTest()"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// +// Assert.assertEquals((new BigInteger(Hex.toHexString(returnValue), 16)).longValue(), curReward); +// +// // Trigger contract method: withdrawRewardTest() +// methodByAddr = "withdrawRewardTest()"; +// +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// +// Assert.assertEquals((new BigInteger(Hex.toHexString(returnValue), 16)).longValue(), curReward); +// +// // Trigger contract method: rewardBalanceTest(address) +// methodByAddr = "rewardBalanceTest(address)"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList(factoryAddressStr)); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // Trigger contract method: withdrawRewardTest() +// methodByAddr = "withdrawRewardTest()"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // Within 24 Hours +// long num = chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber(); +// ByteString latestHeadHash = +// chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderHash().getByteString(); +// blockCapsule = +// createTestBlockCapsule( +// System.currentTimeMillis() + 80400000, +// num + 1, +// latestHeadHash); +// manager.pushBlock(blockCapsule); +// +// // long currentTime = System.currentTimeMillis(); +// // for (int i = 0; i < (86400 / 3 - 3); i++) { +// // currentTime += 3000; +// // ByteString latestHeadHash = chainBaseManager.getDynamicPropertiesStore() +// // .getLatestBlockHeaderHash().getByteString(); +// // blockCapsule = +// // createTestBlockCapsule( +// // currentTime, +// // ++num, +// // latestHeadHash, +// // privateKey); +// // manager.pushBlock(blockCapsule); +// // } +// +// // Trigger contract method: withdrawRewardTest() +// methodByAddr = "withdrawRewardTest()"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// // After 24 Hours +// num = chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber(); +// latestHeadHash = +// chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderHash().getByteString(); +// blockCapsule = +// createTestBlockCapsule( +// System.currentTimeMillis() + 86400000 + 3000, +// num + 1, +// latestHeadHash); +// manager.pushBlock(blockCapsule); +// // for (int i = 0; i < 3; i++) { +// // currentTime += 3000; +// // ByteString latestHeadHash = chainBaseManager.getDynamicPropertiesStore() +// // .getLatestBlockHeaderHash().getByteString(); +// // blockCapsule = +// // createTestBlockCapsule( +// // currentTime, +// // ++num, +// // latestHeadHash, +// // privateKey); +// // manager.pushBlock(blockCapsule); +// // } +// +// // Trigger contract method: withdrawRewardTest() +// methodByAddr = "withdrawRewardTest()"; +// hexInput = AbiUtil.parseMethod(methodByAddr, Collections.singletonList("")); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, blockCapsule); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertNotEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000000"); +// +// ConfigLoader.disable = false; +// } +// +// private BlockCapsule createTestBlockCapsule(long time, +// long number, ByteString hash) { +// ByteString witnessAddress = dposSlot.getScheduledWitness(dposSlot.getSlot(time)); +// BlockCapsule blockCapsule = new BlockCapsule(number, Sha256Hash.wrap(hash), time, +// witnessAddress); +// blockCapsule.generatedByMyself = true; +// blockCapsule.setMerkleRoot(); +// //blockCapsule.sign(privateKey); +// //blockCapsule.sign(ByteArray.fromHexString(privateKey.get(witnessAddress))); +// return blockCapsule; +// } +//} +// +// From af1604ae187d2d1911b0887bf88de9d7c73cfe51 Mon Sep 17 00:00:00 2001 From: xiangdepeng Date: Thu, 5 Nov 2020 17:13:20 +0800 Subject: [PATCH 45/60] remove useless chainParameter --- .../src/main/java/org/tron/core/Wallet.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/framework/src/main/java/org/tron/core/Wallet.java b/framework/src/main/java/org/tron/core/Wallet.java index 98a7410663b..7cebc6f2c05 100755 --- a/framework/src/main/java/org/tron/core/Wallet.java +++ b/framework/src/main/java/org/tron/core/Wallet.java @@ -973,15 +973,15 @@ public Protocol.ChainParameters getChainParameters() { .setValue(dbManager.getDynamicPropertiesStore().getAllowPBFT()) .build()); - builder.addChainParameter(Protocol.ChainParameters.ChainParameter.newBuilder() - .setKey("getAllowTvmStake") - .setValue(dbManager.getDynamicPropertiesStore().getAllowTvmStake()) - .build()); - - builder.addChainParameter(Protocol.ChainParameters.ChainParameter.newBuilder() - .setKey("getAllowTvmAssetIssue") - .setValue(dbManager.getDynamicPropertiesStore().getAllowTvmAssetIssue()) - .build()); + //builder.addChainParameter(Protocol.ChainParameters.ChainParameter.newBuilder() + // .setKey("getAllowTvmStake") + // .setValue(dbManager.getDynamicPropertiesStore().getAllowTvmStake()) + // .build()); + + //builder.addChainParameter(Protocol.ChainParameters.ChainParameter.newBuilder() + // .setKey("getAllowTvmAssetIssue") + // .setValue(dbManager.getDynamicPropertiesStore().getAllowTvmAssetIssue()) + // .build()); return builder.build(); } From eb8016c5c0e80c70a1fbe645d6037eadf3d244cd Mon Sep 17 00:00:00 2001 From: xq-lu <583591aa!!> Date: Mon, 18 Jan 2021 14:24:56 +0800 Subject: [PATCH 46/60] fix checkstyle --- .../org/tron/common/runtime/vm/Trc10Test.java | 18 ++++++++++++------ .../tron/common/runtime/vm/UnStakeTest.java | 12 ++++++++---- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/framework/src/test/java/org/tron/common/runtime/vm/Trc10Test.java b/framework/src/test/java/org/tron/common/runtime/vm/Trc10Test.java index a433ba4f8ae..e9fa65528da 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/Trc10Test.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/Trc10Test.java @@ -182,7 +182,8 @@ // long updateP1 = 1000001; // String updateP2 = "abc"; // String updateP3 = updateP2; -// hexInput = AbiUtil.parseMethod(methodUpdateAsset, Arrays.asList(updateP1, updateP2, updateP3)); +// hexInput = AbiUtil.parseMethod(methodUpdateAsset, +// Arrays.asList(updateP1, updateP2, updateP3)); // result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), // factoryAddress, // Hex.decode(hexInput), value, fee, manager, null); @@ -209,7 +210,8 @@ // + "cabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabca" // + "bcab"; // updateP3 = "efg"; -// hexInput = AbiUtil.parseMethod(methodUpdateAsset, Arrays.asList(updateP1, updateP2, updateP3)); +// hexInput = AbiUtil.parseMethod(methodUpdateAsset, +// Arrays.asList(updateP1, updateP2, updateP3)); // result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), // factoryAddress, // Hex.decode(hexInput), value, fee, manager, null); @@ -228,7 +230,8 @@ // + "bcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcaabcabcabcabcabcabcab" // + "cabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabca"; // updateP2 = "efg"; -// hexInput = AbiUtil.parseMethod(methodUpdateAsset, Arrays.asList(updateP1, updateP2, updateP3)); +// hexInput = AbiUtil.parseMethod(methodUpdateAsset, +// Arrays.asList(updateP1, updateP2, updateP3)); // result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), // factoryAddress, // Hex.decode(hexInput), value, fee, manager, null); @@ -344,7 +347,8 @@ // updateP1 = 1000001; // updateP2 = "abc"; // updateP3 = updateP2; -// hexInput = AbiUtil.parseMethod(methodUpdateAsset, Arrays.asList(updateP1, updateP2, updateP3)); +// hexInput = AbiUtil.parseMethod(methodUpdateAsset, +// Arrays.asList(updateP1, updateP2, updateP3)); // result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), // factoryAddress, // Hex.decode(hexInput), value, fee, manager, null); @@ -525,7 +529,8 @@ // + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}]," // + "\"payable\":false," // + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," -// + "\"inputs\":[{\"internalType\":\"trcToken\",\"name\":\"tokenId\",\"type\":\"trcToken\"}," +// + "\"inputs\":[{\"internalType\":\"trcToken\",\"name\": +// \"tokenId\",\"type\":\"trcToken\"}," // + "{\"internalType\":\"string\",\"name\":\"desc\",\"type\":\"string\"}," // + "{\"internalType\":\"string\"," // + "\"name\":\"url\",\"type\":\"string\"}],\"name\":\"UpdateAsset\",\"outputs\":[]," @@ -633,7 +638,8 @@ // result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), // factoryAddress, // Hex.decode(hexInput), value, fee, manager, null); -// Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 1000001); +// Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), +// 1000001); // Assert.assertNull(result.getRuntime().getRuntimeError()); // // // updateasset test diff --git a/framework/src/test/java/org/tron/common/runtime/vm/UnStakeTest.java b/framework/src/test/java/org/tron/common/runtime/vm/UnStakeTest.java index e115486370b..c25291b24e9 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/UnStakeTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/UnStakeTest.java @@ -55,15 +55,19 @@ // + "\"outputs\":[{\"internalType\":\"uint256\"," // + "\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false," // + "\"stateMutability\":\"nonpayable\"," -// + "\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"address\"," -// + "\"name\":\"sr\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\"," -// + "\"type\":\"uint256\"}],\"name\":\"stakeTest\",\"outputs\":[{\"internalType\":\"bool\"," +// + "\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\" +// :\"address\"," +// + "\"name\":\"sr\",\"type\":\"address\"},{\"internalType\":\"uint256\", +// \"name\":\"amount\"," +// + "\"type\":\"uint256\"}],\"name\":\"stakeTest\",\"outputs\":[{\"internalType\" +// :\"bool\"," // + "\"name\":\"\"," // + "\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," // + "\"type\":\"function\"}," // + "{\"constant\":false,\"inputs\":[],\"name\":\"unstakeTest\"," // + "\"outputs\":[{\"internalType\":\"bool\"," -// + "\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\": +// \"nonpayable\"," // + "\"type\":\"function\"},{\"constant\":false,\"inputs\":[]," // + "\"name\":\"withdrawRewardTest\"," // + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}]," From 8dd0606c1e37b4207d2aa8aa84e0f1b7160d4278 Mon Sep 17 00:00:00 2001 From: xq-lu <583591aa!!> Date: Mon, 18 Jan 2021 15:14:44 +0800 Subject: [PATCH 47/60] fix checkstyle --- .../src/test/java/org/tron/common/runtime/vm/Trc10Test.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/framework/src/test/java/org/tron/common/runtime/vm/Trc10Test.java b/framework/src/test/java/org/tron/common/runtime/vm/Trc10Test.java index e9fa65528da..f6891046375 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/Trc10Test.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/Trc10Test.java @@ -647,7 +647,8 @@ // // 1,abc,abc, // long updateP1 = 1000001; // String updateP2 = "abc"; -// hexInput = AbiUtil.parseMethod(methodUpdateAsset, Arrays.asList(updateP1, updateP2, updateP2)); +// hexInput = AbiUtil.parseMethod(methodUpdateAsset, +// Arrays.asList(updateP1, updateP2, updateP2)); // result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), // factoryAddress, // Hex.decode(hexInput), value, fee, manager, null); From 73a5d8ee36df71946439ecbe9243c94332a463b8 Mon Sep 17 00:00:00 2001 From: zhang0125 Date: Mon, 26 Apr 2021 16:09:45 +0800 Subject: [PATCH 48/60] fix debian test --- .../java/org/tron/core/db/KhaosDatabase.java | 82 ------------------- 1 file changed, 82 deletions(-) diff --git a/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java b/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java index 8d0b02a8943..6da2ed4bd42 100644 --- a/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java +++ b/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java @@ -31,84 +31,6 @@ @Slf4j(topic = "DB") public class KhaosDatabase extends TronDatabase { - public static class Log { - Object blk_begin; - Object blk_prev; - Object head_begin; - Object head_prev; - Object mini_store_begin; - Object mini_store_prev; - Object maxCapcity_begin; - Object maxCapcity_prev; - Object numKblkMap_begin; - Object numKblkMap_prev; - Object hashKblkMap_begin; - Object hashKblkMap_prev; - Object head_num_begin; - Object head_num_prev; - - public void setBlk_begin(Object blk_begin) { - this.blk_prev = this.blk_begin; - this.blk_begin = blk_begin; - } - - public void setHead_begin(Object head_begin) { - this.head_prev = this.head_begin; - this.head_begin = head_begin; - } - - public void setMini_store_begin(Object mini_store_begin) { - this.mini_store_prev = this.mini_store_begin; - this.mini_store_begin = mini_store_begin; - } - - public void setMaxCapcity_begin(Object maxCapcity_begin) { - this.maxCapcity_prev = this.maxCapcity_begin; - this.maxCapcity_begin = maxCapcity_begin; - } - - public void setNumKblkMap_begin(Object numKblkMap_begin) { - this.numKblkMap_prev = this.numKblkMap_begin; - this.numKblkMap_begin = numKblkMap_begin; - } - - public void setHashKblkMap_begin(Object hashKblkMap_begin) { - this.hashKblkMap_prev = this.hashKblkMap_begin; - this.hashKblkMap_begin = hashKblkMap_begin; - } - - public void setHead_num_begin(Object head_num_begin) { - this.head_num_prev = this.head_num_begin; - this.head_num_begin = head_num_begin; - } - - public void print() { - logger.info("********************** " + this.toString()); - } - - @Override - public String toString() { - return "Log{" + - "blk_begin=" + blk_begin + - ", blk_prev=" + blk_prev + - ", head_begin=" + head_begin + - ", head_prev=" + head_prev + - ", mini_store_begin=" + mini_store_begin + - ", mini_store_prev=" + mini_store_prev + - ", maxCapcity_begin=" + maxCapcity_begin + - ", maxCapcity_prev=" + maxCapcity_prev + - ", numKblkMap_begin=" + numKblkMap_begin + - ", numKblkMap_prev=" + numKblkMap_prev + - ", hashKblkMap_begin=" + hashKblkMap_begin + - ", hashKblkMap_prev=" + hashKblkMap_prev + - ", head_num_begin=" + head_num_begin + - ", head_num_prev=" + head_num_prev + - '}'; - } - } - - public static Log log = new Log(); - private KhaosBlock head; @Getter private KhaosStore miniStore = new KhaosStore(); @@ -182,9 +104,6 @@ public BlockCapsule getBlock(Sha256Hash hash) { */ public BlockCapsule push(BlockCapsule blk) throws UnLinkedBlockException, BadNumberBlockException { - log.setBlk_begin(blk); - log.setHead_begin(blk); - log.setMini_store_begin(miniStore); KhaosBlock block = new KhaosBlock(blk); if (head != null && block.getParentHash() != Sha256Hash.ZERO_HASH) { KhaosBlock kblock = miniStore.getByHash(block.getParentHash()); @@ -195,7 +114,6 @@ public BlockCapsule push(BlockCapsule blk) } block.setParent(kblock); } else { - log.print(); miniUnlinkedStore.insert(block); logger.error("blk:{}, head:{}, miniStore:{}, miniUnlinkedStore:{}", blk, From b4252bef6a33c045bdd4a7585d67c980d8d5d013 Mon Sep 17 00:00:00 2001 From: lvs007 Date: Sat, 31 Jul 2021 13:42:26 +0800 Subject: [PATCH 49/60] fix conflicting --- .../actuator/MarketSellAssetActuator.java | 1 + .../org/tron/core/utils/ProposalUtil.java | 1 - .../java/org/tron/core/db/KhaosDatabase.java | 2 +- .../org/tron/consensus/dpos/StateManager.java | 3 +- .../consensus/pbft/message/PbftMessage.java | 1 - .../java/org/tron/core/config/args/Args.java | 1 + .../org/tron/core/services/RpcApiService.java | 22 +- .../services/http/FullNodeHttpApiService.java | 1 - .../solidity/SolidityNodeHttpApiService.java | 20 +- .../solidity/HttpApiOnSolidityService.java | 20 +- .../src/main/resources/config-localtest.conf | 5 + .../org/tron/common/runtime/vm/Trc10Test.java | 666 ++++++++++++++++++ .../tron/common/runtime/vm/UnStakeTest.java | 133 ++++ .../common/runtime/vm/VMContractTestBase.java | 1 - 14 files changed, 840 insertions(+), 37 deletions(-) create mode 100644 framework/src/test/java/org/tron/common/runtime/vm/Trc10Test.java create mode 100644 framework/src/test/java/org/tron/common/runtime/vm/UnStakeTest.java diff --git a/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java b/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java index 15e5a98f86a..04686a67919 100644 --- a/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java @@ -315,6 +315,7 @@ private void matchOrder(MarketOrderCapsule takerCapsule, MarketPrice takerPrice, // makerPair not exists long makerPriceNumber = pairToPriceStore.getPriceNum(makerPair); + if (makerPriceNumber == 0) { return; } diff --git a/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java b/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java index 277bf2f6957..8eac01b9322 100644 --- a/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java +++ b/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java @@ -293,7 +293,6 @@ public static void validator(DynamicPropertiesStore dynamicPropertiesStore, // } case FORBID_TRANSFER_TO_CONTRACT: { if (!forkController.pass(ForkBlockVersionEnum.VERSION_3_6_6)) { - throw new ContractValidateException(BAD_PARAM_ID); } if (value != 1) { diff --git a/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java b/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java index 9c9c968aa73..6da2ed4bd42 100644 --- a/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java +++ b/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java @@ -197,7 +197,7 @@ public Pair, LinkedList> getBranch(Sha256Hash return new Pair<>(list1, list2); } - + private void checkNull(Object o) throws NonCommonBlockException { if (o == null) { throw new NonCommonBlockException(); diff --git a/consensus/src/main/java/org/tron/consensus/dpos/StateManager.java b/consensus/src/main/java/org/tron/consensus/dpos/StateManager.java index df74b64fec8..ba4c48eed94 100644 --- a/consensus/src/main/java/org/tron/consensus/dpos/StateManager.java +++ b/consensus/src/main/java/org/tron/consensus/dpos/StateManager.java @@ -51,13 +51,14 @@ public State getState() { return State.DUP_WITNESS; } - int participation = consensusDelegate.calculateFilledSlotsCount(); + /*int participation = consensusDelegate.calculateFilledSlotsCount(); int minParticipationRate = dposService.getMinParticipationRate(); if (participation < minParticipationRate) { logger .warn("Participation:{} < minParticipationRate:{}", participation, minParticipationRate); return State.LOW_PARTICIPATION; } + */ return State.OK; } diff --git a/consensus/src/main/java/org/tron/consensus/pbft/message/PbftMessage.java b/consensus/src/main/java/org/tron/consensus/pbft/message/PbftMessage.java index b6de49ee878..d157c1f8335 100644 --- a/consensus/src/main/java/org/tron/consensus/pbft/message/PbftMessage.java +++ b/consensus/src/main/java/org/tron/consensus/pbft/message/PbftMessage.java @@ -5,7 +5,6 @@ import org.tron.common.crypto.ECKey; import org.tron.common.crypto.ECKey.ECDSASignature; import org.tron.common.utils.Sha256Hash; -import org.tron.consensus.base.Param; import org.tron.consensus.base.Param.Miner; import org.tron.core.capsule.BlockCapsule; import org.tron.core.net.message.MessageTypes; diff --git a/framework/src/main/java/org/tron/core/config/args/Args.java b/framework/src/main/java/org/tron/core/config/args/Args.java index d159f1ad243..a958c84c082 100644 --- a/framework/src/main/java/org/tron/core/config/args/Args.java +++ b/framework/src/main/java/org/tron/core/config/args/Args.java @@ -1094,6 +1094,7 @@ public static void logConfig() { logger.info("\n"); } + public static void setFullNodeAllowShieldedTransaction(boolean fullNodeAllowShieldedTransaction) { PARAMETER.fullNodeAllowShieldedTransactionArgs = fullNodeAllowShieldedTransaction; } diff --git a/framework/src/main/java/org/tron/core/services/RpcApiService.java b/framework/src/main/java/org/tron/core/services/RpcApiService.java index 241539c2e62..0f2926ab862 100755 --- a/framework/src/main/java/org/tron/core/services/RpcApiService.java +++ b/framework/src/main/java/org/tron/core/services/RpcApiService.java @@ -858,7 +858,7 @@ public void getMarketPriceByPair(MarketOrderPair request, } @Override - public void getMarketOrderListByPair(org.tron.protos.Protocol.MarketOrderPair request, + public void getMarketOrderListByPair(MarketOrderPair request, StreamObserver responseObserver) { try { MarketOrderList orderPairList = wallet @@ -2129,7 +2129,7 @@ public void getNewShieldedAddress(EmptyMessage request, StreamObserver responseObserver) { try { - checkSupportShieldedTRC20Transaction(); + checkSupportShieldedTransaction(); responseObserver.onNext(wallet.getNewShieldedAddress()); } catch (Exception e) { @@ -2143,7 +2143,7 @@ public void getNewShieldedAddress(EmptyMessage request, public void getSpendingKey(EmptyMessage request, StreamObserver responseObserver) { try { - checkSupportShieldedTRC20Transaction(); + checkSupportShieldedTransaction(); responseObserver.onNext(wallet.getSpendingKey()); } catch (Exception e) { @@ -2157,7 +2157,7 @@ public void getSpendingKey(EmptyMessage request, public void getRcm(EmptyMessage request, StreamObserver responseObserver) { try { - checkSupportShieldedTRC20Transaction(); + checkSupportShieldedTransaction(); responseObserver.onNext(wallet.getRcm()); } catch (Exception e) { @@ -2173,7 +2173,7 @@ public void getExpandedSpendingKey(BytesMessage request, ByteString spendingKey = request.getValue(); try { - checkSupportShieldedTRC20Transaction(); + checkSupportShieldedTransaction(); ExpandedSpendingKeyMessage response = wallet.getExpandedSpendingKey(spendingKey); responseObserver.onNext(response); @@ -2190,7 +2190,7 @@ public void getAkFromAsk(BytesMessage request, StreamObserver resp ByteString ak = request.getValue(); try { - checkSupportShieldedTRC20Transaction(); + checkSupportShieldedTransaction(); responseObserver.onNext(wallet.getAkFromAsk(ak)); } catch (BadItemException | ZksnarkException e) { @@ -2206,7 +2206,7 @@ public void getNkFromNsk(BytesMessage request, StreamObserver resp ByteString nk = request.getValue(); try { - checkSupportShieldedTRC20Transaction(); + checkSupportShieldedTransaction(); responseObserver.onNext(wallet.getNkFromNsk(nk)); } catch (BadItemException | ZksnarkException e) { @@ -2224,7 +2224,7 @@ public void getIncomingViewingKey(ViewingKeyMessage request, ByteString nk = request.getNk(); try { - checkSupportShieldedTRC20Transaction(); + checkSupportShieldedTransaction(); responseObserver.onNext(wallet.getIncomingViewingKey(ak.toByteArray(), nk.toByteArray())); } catch (ZksnarkException e) { @@ -2239,7 +2239,7 @@ public void getIncomingViewingKey(ViewingKeyMessage request, public void getDiversifier(EmptyMessage request, StreamObserver responseObserver) { try { - checkSupportShieldedTRC20Transaction(); + checkSupportShieldedTransaction(); DiversifierMessage d = wallet.getDiversifier(); responseObserver.onNext(d); @@ -2258,7 +2258,7 @@ public void getZenPaymentAddress(IncomingViewingKeyDiversifierMessage request, DiversifierMessage d = request.getD(); try { - checkSupportShieldedTRC20Transaction(); + checkSupportShieldedTransaction(); PaymentAddressMessage saplingPaymentAddressMessage = wallet.getPaymentAddress(new IncomingViewingKey(ivk.getIvk().toByteArray()), @@ -2367,7 +2367,7 @@ public void createShieldNullifier(GrpcAPI.NfParameters request, public void createSpendAuthSig(SpendAuthSigParameters request, StreamObserver responseObserver) { try { - checkSupportShieldedTRC20Transaction(); + checkSupportShieldedTransaction(); BytesMessage spendAuthSig = wallet.createSpendAuthSig(request); responseObserver.onNext(spendAuthSig); diff --git a/framework/src/main/java/org/tron/core/services/http/FullNodeHttpApiService.java b/framework/src/main/java/org/tron/core/services/http/FullNodeHttpApiService.java index 1c219f35bbf..bf520ac7219 100644 --- a/framework/src/main/java/org/tron/core/services/http/FullNodeHttpApiService.java +++ b/framework/src/main/java/org/tron/core/services/http/FullNodeHttpApiService.java @@ -479,7 +479,6 @@ public void start() { // "/wallet/createshieldnullifier"); // context.addServlet(new ServletHolder(getShieldTransactionHashServlet), // "/wallet/getshieldtransactionhash"); - context .addServlet(new ServletHolder(isShieldedTRC20ContractNoteSpentServlet), "/wallet/isshieldedtrc20contractnotespent"); diff --git a/framework/src/main/java/org/tron/core/services/http/solidity/SolidityNodeHttpApiService.java b/framework/src/main/java/org/tron/core/services/http/solidity/SolidityNodeHttpApiService.java index 0a3ff9eef4f..52daceaaff5 100644 --- a/framework/src/main/java/org/tron/core/services/http/solidity/SolidityNodeHttpApiService.java +++ b/framework/src/main/java/org/tron/core/services/http/solidity/SolidityNodeHttpApiService.java @@ -191,16 +191,16 @@ public void start() { context.addServlet(new ServletHolder(getBlockByLatestNumServlet), "/walletsolidity/getblockbylatestnum"); - // context.addServlet(new ServletHolder(getMerkleTreeVoucherInfoServlet), - // "/walletsolidity/getmerkletreevoucherinfo"); - // context.addServlet(new ServletHolder(scanAndMarkNoteByIvkServlet), - // "/walletsolidity/scanandmarknotebyivk"); - // context.addServlet(new ServletHolder(scanNoteByIvkServlet), - // "/walletsolidity/scannotebyivk"); - // context.addServlet(new ServletHolder(scanNoteByOvkServlet), - // "/walletsolidity/scannotebyovk"); - // context.addServlet(new ServletHolder(isSpendServlet), - // "/walletsolidity/isspend"); + context.addServlet(new ServletHolder(getMerkleTreeVoucherInfoServlet), + "/walletsolidity/getmerkletreevoucherinfo"); + context.addServlet(new ServletHolder(scanAndMarkNoteByIvkServlet), + "/walletsolidity/scanandmarknotebyivk"); + context.addServlet(new ServletHolder(scanNoteByIvkServlet), + "/walletsolidity/scannotebyivk"); + context.addServlet(new ServletHolder(scanNoteByOvkServlet), + "/walletsolidity/scannotebyovk"); + context.addServlet(new ServletHolder(isSpendServlet), + "/walletsolidity/isspend"); context.addServlet(new ServletHolder(scanShieldedTRC20NotesByIvkServlet), "/walletsolidity/scanshieldedtrc20notesbyivk"); diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/solidity/HttpApiOnSolidityService.java b/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/solidity/HttpApiOnSolidityService.java index 8165abbb275..29f622e80ef 100644 --- a/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/solidity/HttpApiOnSolidityService.java +++ b/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/http/solidity/HttpApiOnSolidityService.java @@ -199,16 +199,16 @@ public void start() { "/walletsolidity/getblockbylimitnext"); context.addServlet(new ServletHolder(getBlockByLatestNumOnSolidityServlet), "/walletsolidity/getblockbylatestnum"); - // context.addServlet(new ServletHolder(getMerkleTreeVoucherInfoOnSolidityServlet), - // "/walletsolidity/getmerkletreevoucherinfo"); - // context.addServlet(new ServletHolder(scanAndMarkNoteByIvkOnSolidityServlet), - // "/walletsolidity/scanandmarknotebyivk"); - // context.addServlet(new ServletHolder(scanNoteByIvkOnSolidityServlet), - // "/walletsolidity/scannotebyivk"); - // context.addServlet(new ServletHolder(scanNoteByOvkOnSolidityServlet), - // "/walletsolidity/scannotebyovk"); - // context.addServlet(new ServletHolder(isSpendOnSolidityServlet), - // "/walletsolidity/isspend"); + context.addServlet(new ServletHolder(getMerkleTreeVoucherInfoOnSolidityServlet), + "/walletsolidity/getmerkletreevoucherinfo"); + context.addServlet(new ServletHolder(scanAndMarkNoteByIvkOnSolidityServlet), + "/walletsolidity/scanandmarknotebyivk"); + context.addServlet(new ServletHolder(scanNoteByIvkOnSolidityServlet), + "/walletsolidity/scannotebyivk"); + context.addServlet(new ServletHolder(scanNoteByOvkOnSolidityServlet), + "/walletsolidity/scannotebyovk"); + context.addServlet(new ServletHolder(isSpendOnSolidityServlet), + "/walletsolidity/isspend"); context.addServlet(new ServletHolder(scanShieldedTRC20NotesByIvkOnSolidityServlet), "/walletsolidity/scanshieldedtrc20notesbyivk"); context.addServlet(new ServletHolder(scanShieldedTRC20NotesByOvkOnSolidityServlet), diff --git a/framework/src/main/resources/config-localtest.conf b/framework/src/main/resources/config-localtest.conf index a9a56591800..a76aa996e98 100644 --- a/framework/src/main/resources/config-localtest.conf +++ b/framework/src/main/resources/config-localtest.conf @@ -96,6 +96,10 @@ node { minParticipationRate = 0 + fullNodeAllowShieldedTransaction = true + + zenTokenId = 1000001 + # check the peer data transfer ,disconnect factor disconnectNumberFactor = 0.4 maxConnectNumberFactor = 0.8 @@ -272,6 +276,7 @@ vm = { committee = { allowCreationOfContracts = 1 //mainnet:0 (reset by committee),test:1 allowMultiSign = 1 //mainnet:0 (reset by committee),test:1 + allowShieldedTransaction = 1 //mainnet:0 (reset by committee),test:1 allowSameTokenName = 1 allowTvmTransferTrc10 = 1 allowTvmConstantinople = 1 diff --git a/framework/src/test/java/org/tron/common/runtime/vm/Trc10Test.java b/framework/src/test/java/org/tron/common/runtime/vm/Trc10Test.java new file mode 100644 index 00000000000..f6891046375 --- /dev/null +++ b/framework/src/test/java/org/tron/common/runtime/vm/Trc10Test.java @@ -0,0 +1,666 @@ +//package org.tron.common.runtime.vm; +// +//import static stest.tron.wallet.common.client.utils.PublicMethed.decode58Check; +// +//import java.util.Arrays; +//import java.util.Collections; +//import lombok.extern.slf4j.Slf4j; +//import org.junit.Test; +//import org.spongycastle.util.encoders.Hex; +//import org.testng.Assert; +//import org.tron.common.runtime.TVMTestResult; +//import org.tron.common.runtime.TvmTestUtils; +//import org.tron.common.utils.ByteArray; +//import org.tron.common.utils.WalletUtil; +//import org.tron.core.exception.ContractExeException; +//import org.tron.core.exception.ContractValidateException; +//import org.tron.core.exception.ReceiptCheckErrException; +//import org.tron.core.exception.VMIllegalException; +//import org.tron.core.vm.config.ConfigLoader; +//import org.tron.core.vm.config.VMConfig; +//import org.tron.protos.Protocol; +//import stest.tron.wallet.common.client.utils.AbiUtil; +// +//@Slf4j +//public class Trc10Test extends VMContractTestBase { +// +// /*pragma solidity ^0.5.12; +// contract HelloWorld{ +// function TokenIssue(bytes32 name, bytes32 abbr, uint64 +// totalSupply, uint8 precision) public returns (uint) { +// return assetissue(name, abbr, totalSupply, precision); +// } +// function UpdateAsset(trcToken tokenId, string memory url, string +// memory desc) public { +// updateasset(tokenId, bytes(url), bytes(desc)); +// } +// }*/ +// @Test +// public void testTrc10Validate() throws ContractExeException, +// ReceiptCheckErrException, VMIllegalException, +// ContractValidateException { +// ConfigLoader.disable = true; +// VMConfig.initAllowTvmTransferTrc10(1); +// VMConfig.initAllowTvmConstantinople(1); +// VMConfig.initAllowTvmSolidity059(1); +// VMConfig.initAllowTvmAssetIssue(1); +// manager.getDynamicPropertiesStore().saveAllowSameTokenName(1); +// String contractName = "AssetIssueTest"; +// byte[] address = Hex.decode(OWNER_ADDRESS); +// String abi = "[{\"constant\":false," +// + "\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"name\"," +// + "\"type\":\"bytes32\"},{\"internalType\":\"bytes32\"," +// + "\"name\":\"abbr\",\"type\":\"bytes32\"}," +// + "{\"internalType\":\"uint64\",\"name\":\"totalSupply\"," +// + "\"type\":\"uint64\"},{\"internalType\":\"uint8\"," +// + "\"name\":\"precision\",\"type\":\"uint8\"}]," +// + "\"name\":\"TokenIssue\"," +// + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\"," +// + "\"type\":\"uint256\"}],\"payable\":false," +// + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," +// + "{\"constant\":false,\"inputs\":[{\"internalType\":\"trcToken" +// + "\",\"name\":\"tokenId\",\"type\":\"trcToken\"}," +// + "{\"internalType\":\"string\",\"name\":\"desc\"," +// + "\"type\":\"string\"},{\"internalType\":\"string\"," +// + "\"name\":\"url\",\"type\":\"string\"}]," +// + "\"name\":\"UpdateAsset\",\"outputs\":[],\"payable\":false," +// + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"; +// String factoryCode = +// "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a576000" +// + "80fd5b506102938061003a6000396000f3fe608060405234801561001057600080fd5b50d3801561" +// + "001d57600080fd5b50d2801561002a57600080fd5b50600436106100505760003560e01c80633615" +// + "673e14610055578063f177bc7a146100c2575b600080fd5b6100ac6004803603608081101561006b" +// + "57600080fd5b810190808035906020019092919080359060200190929190803567ffffffffffffff" +// + "ff169060200190929190803560ff16906020019092919050505061021e565b604051808281526020" +// + "0191505060405180910390f35b61021c600480360360608110156100d857600080fd5b8101908080" +// + "359060200190929190803590602001906401000000008111156100ff57600080fd5b820183602082" +// + "01111561011157600080fd5b80359060200191846001830284011164010000000083111715610133" +// + "57600080fd5b91908080601f01602080910402602001604051908101604052809392919081815260" +// + "2001838380828437600081840152601f19601f820116905080830192505050505050509192919290" +// + "8035906020019064010000000081111561019657600080fd5b8201836020820111156101a8576000" +// + "80fd5b803590602001918460018302840111640100000000831117156101ca57600080fd5b919080" +// + "80601f01602080910402602001604051908101604052809392919081815260200183838082843760" +// + "0081840152601f19601f82011690508083019250505050505050919291929050505061022f565b00" +// + "5b600081838587da9050949350505050565b808284db5050505056fea26474726f6e5820def53e9f" +// + "ef23475f8f3316cfaf66a0015e2205fe9bf0eba01f703e30ef9d732364736f6c637828302e352e31" +// + "332d646576656c6f702e323032302e382e31332b636f6d6d69742e37633236393863300057"; +// long value = 0; +// long fee = 100000000; +// long consumeUserResourcePercent = 0; +// // deploy contract +// Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, +// null); +// byte[] factoryAddress = WalletUtil.generateContractAddress(trx); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); +// Assert.assertNull(runtime.getRuntimeError()); +// +// // validate balance is enough +// String tokenP1 = "74657374"; +// String tokenP2 = tokenP1; +// long tokenP3 = 1000; +// long tokenP4 = 2; +// String methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8)"; +// String hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP2, +// tokenP3, tokenP4)); +// TVMTestResult result = +// TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 0); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// rootRepository.addBalance(factoryAddress, 10000000000L); +// rootRepository.commit(); +// Assert.assertEquals(rootRepository.getBalance(factoryAddress), 10000000000L); +// +// // validate assetissue assetname can't be trx +// tokenP1 = "747278"; +// tokenP2 = tokenP1; +// tokenP3 = 1000; +// tokenP4 = 2; +// methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8)"; +// hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP2, tokenP3, +// tokenP4)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 0); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// // validate assetissue precision can't more than 6 +// tokenP1 = "74657374"; +// tokenP2 = tokenP1; +// tokenP3 = 1000; +// tokenP4 = 7; +// methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8)"; +// hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP2, tokenP3, +// tokenP4)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 0); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// // trigger contract success +// tokenP1 = "74657374"; +// tokenP2 = tokenP1; +// tokenP3 = 1000; +// tokenP4 = 2; +// methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8)"; +// hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP2, tokenP3, +// tokenP4)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 1000001); +// long expectEnergyUsageTotal = 25000; +// long expectEnergyUsageTotalMax = 30000; +// long reallyEnergyUsageTotal = result.getReceipt().getEnergyUsageTotal(); +// // validate energy cost +// Assert.assertTrue(reallyEnergyUsageTotal > expectEnergyUsageTotal +// && reallyEnergyUsageTotal < expectEnergyUsageTotalMax); +// +// // validate assetissue An account can only issue one asset +// tokenP1 = "74657374"; +// tokenP2 = tokenP1; +// tokenP3 = 1000; +// tokenP4 = 2; +// methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8)"; +// hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP2, tokenP3, +// tokenP4)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 0); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// // Trigger contract method: UpdateAsset(trcToken, string, string) +// String methodUpdateAsset = "UpdateAsset(trcToken,string,string)"; +// // 1,abc,abc, +// long updateP1 = 1000001; +// String updateP2 = "abc"; +// String updateP3 = updateP2; +// hexInput = AbiUtil.parseMethod(methodUpdateAsset, +// Arrays.asList(updateP1, updateP2, updateP3)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() +// .get(0).getUrl().toByteArray()), "abc"); +// Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() +// .get(0).getDesc().toByteArray()), "abc"); +// // validate energy cost +// expectEnergyUsageTotal = 5000; +// expectEnergyUsageTotalMax = 10000; +// reallyEnergyUsageTotal = result.getReceipt().getEnergyUsageTotal(); +// +// Assert.assertTrue(reallyEnergyUsageTotal > expectEnergyUsageTotal +// && reallyEnergyUsageTotal < expectEnergyUsageTotalMax); +// +// // validate desc less than 200 +// updateP1 = 1000001; +// updateP2 = +// "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcab" +// + "cabcabcabcabcabcabcababcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcab" +// + "cabcabcabcabcabcabcabcabcabcabcabcabcabcababcabcabcabcabcabcabcabcabcabcabcabcab" +// + "cabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcababcabcabcabcabcab" +// + "cabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabca" +// + "bcab"; +// updateP3 = "efg"; +// hexInput = AbiUtil.parseMethod(methodUpdateAsset, +// Arrays.asList(updateP1, updateP2, updateP3)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() +// .get(0).getUrl().toByteArray()), "abc"); +// Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() +// .get(0).getDesc().toByteArray()), "abc"); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// // validate url less than 256 +// updateP1 = 1000001; +// updateP3 = +// "abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcab" +// + "cabcabcabcabcabcabcaabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabc" +// + "abcabcabcabcabcabcabcabcabcabcabcabcabcaabcabcabcabcabcabcabcabcabcabcabcabcabca" +// + "bcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcaabcabcabcabcabcabcab" +// + "cabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabca"; +// updateP2 = "efg"; +// hexInput = AbiUtil.parseMethod(methodUpdateAsset, +// Arrays.asList(updateP1, updateP2, updateP3)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// } +// +// /*pragma solidity ^0.5.12; +// contract HelloWorld{ +// function TokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) +// public { +// assetissue(name, abbr, totalSupply, precision); +// assetissue(name, abbr, totalSupply, precision); +// } +// function UpdateAsset(trcToken tokenId, string memory url, string memory desc) public { +// updateasset(tokenId, bytes(url), bytes(desc)); +// updateasset(tokenId, bytes(url), bytes(desc)); +// } +// }*/ +// +// @Test +// public void testTrc10ForMultiCall() throws ContractExeException, +// ReceiptCheckErrException, VMIllegalException, +// ContractValidateException { +// ConfigLoader.disable = true; +// VMConfig.initAllowTvmTransferTrc10(1); +// VMConfig.initAllowTvmConstantinople(1); +// VMConfig.initAllowTvmSolidity059(1); +// VMConfig.initAllowTvmAssetIssue(1); +// manager.getDynamicPropertiesStore().saveAllowSameTokenName(1); +// String contractName = "AssetIssueTest"; +// byte[] address = Hex.decode(OWNER_ADDRESS); +// String abi = "[{\"constant\":false,\"inputs\":[{\"internalType\":\"bytes32\"," +// + "\"name\":\"name\"," +// + "\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"abbr\"," +// + "\"type\":\"bytes32\"}," +// + "{\"internalType\":\"uint64\",\"name\":\"totalSupply\",\"type\":\"uint64\"}," +// + "{\"internalType\":\"uint8\",\"name\":\"precision\",\"type\":\"uint8\"}]," +// + "\"name\":\"TokenIssue\"," +// + "\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"function\"}," +// + "{\"constant\":false,\"inputs\":[{\"internalType\":\"trcToken\",\"name\":\"tokenId\"," +// + "\"type\":\"trcToken\"},{\"internalType\":\"string\",\"name\":\"desc\"," +// + "\"type\":\"string\"}," +// + "{\"internalType\":\"string\",\"name\":\"url\",\"type\":\"string\"}]," +// + "\"name\":\"UpdateAsset\"," +// + "\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"function\"}]"; +// String factoryCode = +// "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a576000" +// + "80fd5b506102858061003a6000396000f3fe608060405234801561001057600080fd5b50d3801561" +// + "001d57600080fd5b50d2801561002a57600080fd5b50600436106100505760003560e01c80633615" +// + "673e14610055578063f177bc7a146100ae575b600080fd5b6100ac6004803603608081101561006b" +// + "57600080fd5b810190808035906020019092919080359060200190929190803567ffffffffffffff" +// + "ff169060200190929190803560ff16906020019092919050505061020a565b005b61020860048036" +// + "0360608110156100c457600080fd5b81019080803590602001909291908035906020019064010000" +// + "00008111156100eb57600080fd5b8201836020820111156100fd57600080fd5b8035906020019184" +// + "600183028401116401000000008311171561011f57600080fd5b91908080601f0160208091040260" +// + "20016040519081016040528093929190818152602001838380828437600081840152601f19601f82" +// + "01169050808301925050505050505091929192908035906020019064010000000081111561018257" +// + "600080fd5b82018360208201111561019457600080fd5b8035906020019184600183028401116401" +// + "00000000831117156101b657600080fd5b91908080601f0160208091040260200160405190810160" +// + "40528093929190818152602001838380828437600081840152601f19601f82011690508083019250" +// + "505050505050919291929050505061021c565b005b80828486da5080828486da5050505050565b80" +// + "8284db50808284db5050505056fea26474726f6e582010b72c10cc2d93a0ddc6ec14e8a40345f73a" +// + "2263120bd04e1552687570eb950c64736f6c637828302e352e31332d646576656c6f702e32303230" +// + "2e382e31332b636f6d6d69742e37633236393863300057"; +// long value = 0; +// long fee = 100000000; +// long consumeUserResourcePercent = 0; +// // deploy contract +// Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, +// null); +// byte[] factoryAddress = WalletUtil.generateContractAddress(trx); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); +// Assert.assertNull(runtime.getRuntimeError()); +// +// // send coin +// rootRepository.addBalance(factoryAddress, 10000000000L); +// rootRepository.commit(); +// Assert.assertEquals(rootRepository.getBalance(factoryAddress), 10000000000L); +// +// // validate updateasset Asset is not existed in AssetIssueStore +// String methodUpdateAsset = "UpdateAsset(trcToken,string,string)"; +// // 1,abc,abc, +// long updateP1 = 1000001; +// String updateP2 = "616263"; +// String updateP3 = updateP2; +// String hexInput = AbiUtil.parseMethod(methodUpdateAsset, Arrays.asList(updateP1, updateP2, +// updateP3)); +// TVMTestResult result = +// TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// // multicall tokenissue +// String tokenP1 = "74657374"; +// long tokenP3 = 1000; +// long tokenP4 = 2; +// String methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8)"; +// hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP1, tokenP3, +// tokenP4)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 0); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// // multicall updateAsset +// methodUpdateAsset = "UpdateAsset(trcToken,string,string)"; +// // 1,abc,abc, +// updateP1 = 1000001; +// updateP2 = "abc"; +// updateP3 = updateP2; +// hexInput = AbiUtil.parseMethod(methodUpdateAsset, +// Arrays.asList(updateP1, updateP2, updateP3)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() +// .get(0).getUrl().toByteArray()), +// "abc"); +// Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() +// .get(0).getDesc().toByteArray()), +// "abc"); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// } +// +// /*pragma solidity ^0.5.12; +// contract HelloWorld{ +// function TokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision, +// address addr) public { +// address payable newaddress = address(uint160(addr)); +// newaddress.transfer(100000000); +// assetissue(name, abbr, totalSupply, precision); +// newaddress.transfer(100000000); +// } +// function UpdateAsset(trcToken tokenId, string memory url, string memory desc, address +// addr) public { +// address payable newaddress = address(uint160(addr)); +// newaddress.transfer(100000000); +// updateasset(tokenId, bytes(url), bytes(desc)); +// newaddress.transfer(100000000); +// } +// }*/ +// +// @Test +// public void testTrc10Exception() throws ContractExeException, +// ReceiptCheckErrException, VMIllegalException, +// ContractValidateException { +// ConfigLoader.disable = true; +// VMConfig.initAllowTvmTransferTrc10(1); +// VMConfig.initAllowTvmConstantinople(1); +// VMConfig.initAllowTvmSolidity059(1); +// VMConfig.initAllowTvmAssetIssue(1); +// String contractName = "AssetIssueTest"; +// byte[] address = Hex.decode(OWNER_ADDRESS); +// String abi = "[{\"constant\":false,\"inputs\":[{\"internalType\":\"bytes32\"," +// + "\"name\":\"name\"," +// + "\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"abbr\"," +// + "\"type\":\"bytes32\"}," +// + "{\"internalType\":\"uint64\",\"name\":\"totalSupply\",\"type\":\"uint64\"}," +// + "{\"internalType\":\"uint8\",\"name\":\"precision\",\"type\":\"uint8\"}," +// + "{\"internalType\":\"address\",\"name\":\"addr\",\"type\":\"address\"}]," +// + "\"name\":\"TokenIssue\"," +// + "\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"function\"}," +// + "{\"constant\":false,\"inputs\":[{\"internalType\":\"trcToken\",\"name\":\"tokenId\"," +// + "\"type\":\"trcToken\"},{\"internalType\":\"string\",\"name\":\"desc\"," +// + "\"type\":\"string\"}," +// + "{\"internalType\":\"string\",\"name\":\"url\",\"type\":\"string\"}," +// + "{\"internalType\":\"address\"," +// + "\"name\":\"addr\",\"type\":\"address\"}],\"name\":\"UpdateAsset\",\"outputs\":[]," +// + "\"payable\":false," +// + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"; +// String factoryCode = +// "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a576000" +// + "80fd5b506103f48061003a6000396000f3fe608060405234801561001057600080fd5b50d3801561" +// + "001d57600080fd5b50d2801561002a57600080fd5b50600436106100505760003560e01c8063451e" +// + "cfa214610055578063a241e431146100ce575b600080fd5b6100cc600480360360a081101561006b" +// + "57600080fd5b810190808035906020019092919080359060200190929190803567ffffffffffffff" +// + "ff169060200190929190803560ff169060200190929190803573ffffffffffffffffffffffffffff" +// + "ffffffffffff16906020019092919050505061024a565b005b610248600480360360808110156100" +// + "e457600080fd5b81019080803590602001909291908035906020019064010000000081111561010b" +// + "57600080fd5b82018360208201111561011d57600080fd5b80359060200191846001830284011164" +// + "01000000008311171561013f57600080fd5b91908080601f01602080910402602001604051908101" +// + "6040528093929190818152602001838380828437600081840152601f19601f820116905080830192" +// + "505050505050509192919290803590602001906401000000008111156101a257600080fd5b820183" +// + "6020820111156101b457600080fd5b80359060200191846001830284011164010000000083111715" +// + "6101d657600080fd5b91908080601f01602080910402602001604051908101604052809392919081" +// + "8152602001838380828437600081840152601f19601f820116905080830192505050505050509192" +// + "919290803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506102" +// + "f3565b005b60008190508073ffffffffffffffffffffffffffffffffffffffff166108fc6305f5e1" +// + "009081150290604051600060405180830381858888f19350505050158015610299573d6000803e3d" +// + "6000fd5b5082848688da508073ffffffffffffffffffffffffffffffffffffffff166108fc6305f5" +// + "e1009081150290604051600060405180830381858888f193505050501580156102ea573d6000803e" +// + "3d6000fd5b50505050505050565b60008190508073ffffffffffffffffffffffffffffffffffffff" +// + "ff166108fc6305f5e1009081150290604051600060405180830381858888f1935050505015801561" +// + "0342573d6000803e3d6000fd5b50828486db508073ffffffffffffffffffffffffffffffffffffff" +// + "ff166108fc6305f5e1009081150290604051600060405180830381858888f1935050505015801561" +// + "0392573d6000803e3d6000fd5b50505050505056fea26474726f6e5820e6e64fe3d21e1866d8b2da" +// + "9e9bba20e7b5fee47cf6122aae388eb63b4d3df07264736f6c637828302e352e31332d646576656c" +// + "6f702e323032302e382e31332b636f6d6d69742e37633236393863300057"; +// long value = 0; +// long fee = 100000000; +// long consumeUserResourcePercent = 0; +// // deploy contract +// Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, +// null); +// byte[] factoryAddress = WalletUtil.generateContractAddress(trx); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); +// Assert.assertNull(runtime.getRuntimeError()); +// +// // sendcoin to factoryAddress 100000000000 +// rootRepository.addBalance(factoryAddress, 10000000000L); +// rootRepository.commit(); +// Assert.assertEquals(rootRepository.getBalance(factoryAddress), 10000000000L); +// +// // assetissue exception test +// String tokenP1 = "74657374"; +// long tokenP3 = 1000; +// long tokenP4 = 7; +// String methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8,address)"; +// String receiveAddress = "27VZHn9PFZwNh7o2EporxmLkpe157iWZVkh"; +// String hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP1, +// tokenP3, tokenP4, receiveAddress)); +// TVMTestResult result = +// TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), 0); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// Assert.assertEquals(200000000, +// rootRepository.getBalance(decode58Check(receiveAddress))); +// +// // updateasset exception test +// String methodUpdateAsset = "UpdateAsset(trcToken,string,string,address)"; +// // 1,abc,abc, +// long updateP1 = 1000001; +// String updateP2 = "616263"; +// hexInput = AbiUtil.parseMethod(methodUpdateAsset, Arrays.asList(updateP1, updateP2, updateP2, +// receiveAddress)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// Assert.assertEquals(200000000, rootRepository.getBalance(decode58Check(receiveAddress))); +// } +// +// /*pragma solidity ^0.5.0; +// contract A { +// function TokenIssueA(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) +// public returns (uint){ +// return assetissue(name, abbr, totalSupply, precision); +// } +// function UpdateAssetA(trcToken tokenId, string memory desc, string memory url) public { +// updateasset(tokenId, bytes(desc), bytes(url)); +// } +// } +// contract HelloWorld { +// A a = new A(); +// function TokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) +// public returns (uint) { +// return a.TokenIssueA(name, abbr, totalSupply, precision); +// } +// function UpdateAsset(trcToken tokenId, string memory url, string memory desc) public { +// a.UpdateAssetA(tokenId, url, desc); +// } +// function getContractAddress() public returns (address) { +// return address(a); +// } +// }*/ +// +// @Test +// public void testTrc10ContractCall() throws ContractExeException, +// ReceiptCheckErrException, VMIllegalException, +// ContractValidateException { +// ConfigLoader.disable = true; +// VMConfig.initAllowTvmTransferTrc10(1); +// VMConfig.initAllowTvmConstantinople(1); +// VMConfig.initAllowTvmSolidity059(1); +// VMConfig.initAllowTvmAssetIssue(1); +// manager.getDynamicPropertiesStore().saveAllowSameTokenName(1); +// String contractName = "AssetIssueTest"; +// byte[] address = Hex.decode(OWNER_ADDRESS); +// String abi = "[{\"constant\":false,\"inputs\":[{\"internalType\":\"bytes32\"," +// + "\"name\":\"name\"," +// + "\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"abbr\"," +// + "\"type\":\"bytes32\"}," +// + "{\"internalType\":\"uint64\",\"name\":\"totalSupply\",\"type\":\"uint64\"}," +// + "{\"internalType\":\"uint8\",\"name\":\"precision\",\"type\":\"uint8\"}]," +// + "\"name\":\"TokenIssue\"," +// + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}]," +// + "\"payable\":false," +// + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," +// + "\"inputs\":[{\"internalType\":\"trcToken\",\"name\": +// \"tokenId\",\"type\":\"trcToken\"}," +// + "{\"internalType\":\"string\",\"name\":\"desc\",\"type\":\"string\"}," +// + "{\"internalType\":\"string\"," +// + "\"name\":\"url\",\"type\":\"string\"}],\"name\":\"UpdateAsset\",\"outputs\":[]," +// + "\"payable\":false," +// + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," +// + "\"inputs\":[]," +// + "\"name\":\"getContractAddress\",\"outputs\":[{\"internalType\":\"address\"," +// + "\"name\":\"\"," +// + "\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"function\"}]"; +// String factoryCode = +// "608060405260405161001090610098565b604051809103906000f08015801561002c573d6000803e" +// + "3d6000fd5b506000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916" +// + "908373ffffffffffffffffffffffffffffffffffffffff16021790555034801561007857600080fd" +// + "5b50d3801561008557600080fd5b50d2801561009257600080fd5b506100a5565b6102cd80610602" +// + "83390190565b61054e806100b46000396000f3fe608060405234801561001057600080fd5b50d380" +// + "1561001d57600080fd5b50d2801561002a57600080fd5b506004361061005b5760003560e01c8063" +// + "32a2c5d0146100605780633615673e146100aa578063f177bc7a14610117575b600080fd5b610068" +// + "610273565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffff" +// + "ffffffffffffffffffffffffff16815260200191505060405180910390f35b610101600480360360" +// + "808110156100c057600080fd5b810190808035906020019092919080359060200190929190803567" +// + "ffffffffffffffff169060200190929190803560ff16906020019092919050505061029c565b6040" +// + "518082815260200191505060405180910390f35b6102716004803603606081101561012d57600080" +// + "fd5b81019080803590602001909291908035906020019064010000000081111561015457600080fd" +// + "5b82018360208201111561016657600080fd5b803590602001918460018302840111640100000000" +// + "8311171561018857600080fd5b91908080601f016020809104026020016040519081016040528093" +// + "929190818152602001838380828437600081840152601f19601f8201169050808301925050505050" +// + "50509192919290803590602001906401000000008111156101eb57600080fd5b8201836020820111" +// + "156101fd57600080fd5b8035906020019184600183028401116401000000008311171561021f5760" +// + "0080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001" +// + "838380828437600081840152601f19601f8201169050808301925050505050505091929192905050" +// + "50610389565b005b60008060009054906101000a900473ffffffffffffffffffffffffffffffffff" +// + "ffffff16905090565b60008060009054906101000a900473ffffffffffffffffffffffffffffffff" +// + "ffffffff1673ffffffffffffffffffffffffffffffffffffffff166329f00e598686868660405185" +// + "63ffffffff1660e01b8152600401808581526020018481526020018367ffffffffffffffff1667ff" +// + "ffffffffffffff1681526020018260ff1660ff168152602001945050505050602060405180830381" +// + "600087803b15801561034457600080fd5b505af1158015610358573d6000803e3d6000fd5b505050" +// + "506040513d602081101561036e57600080fd5b810190808051906020019092919050505090509493" +// + "50505050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff16" +// + "73ffffffffffffffffffffffffffffffffffffffff1663cfa62e758484846040518463ffffffff16" +// + "60e01b81526004018084815260200180602001806020018381038352858181518152602001915080" +// + "51906020019080838360005b83811015610422578082015181840152602081019050610407565b50" +// + "505050905090810190601f16801561044f5780820380516001836020036101000a03191681526020" +// + "0191505b50838103825284818151815260200191508051906020019080838360005b838110156104" +// + "8857808201518184015260208101905061046d565b50505050905090810190601f1680156104b557" +// + "80820380516001836020036101000a031916815260200191505b5095505050505050600060405180" +// + "830381600087803b1580156104d757600080fd5b505af11580156104eb573d6000803e3d6000fd5b" +// + "5050505050505056fea26474726f6e582068c6e59329c5b9e63f34ea5762d58db8649b294831356a" +// + "dfe323a04f3c96c25f64736f6c637828302e352e31332d646576656c6f702e323032302e382e3133" +// + "2b636f6d6d69742e37633236393863300057608060405234801561001057600080fd5b50d3801561" +// + "001d57600080fd5b50d2801561002a57600080fd5b506102938061003a6000396000f3fe60806040" +// + "5234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b50" +// + "600436106100505760003560e01c806329f00e5914610055578063cfa62e75146100c2575b600080" +// + "fd5b6100ac6004803603608081101561006b57600080fd5b81019080803590602001909291908035" +// + "9060200190929190803567ffffffffffffffff169060200190929190803560ff1690602001909291" +// + "9050505061021e565b6040518082815260200191505060405180910390f35b61021c600480360360" +// + "608110156100d857600080fd5b810190808035906020019092919080359060200190640100000000" +// + "8111156100ff57600080fd5b82018360208201111561011157600080fd5b80359060200191846001" +// + "83028401116401000000008311171561013357600080fd5b91908080601f01602080910402602001" +// + "6040519081016040528093929190818152602001838380828437600081840152601f19601f820116" +// + "90508083019250505050505050919291929080359060200190640100000000811115610196576000" +// + "80fd5b8201836020820111156101a857600080fd5b80359060200191846001830284011164010000" +// + "0000831117156101ca57600080fd5b91908080601f01602080910402602001604051908101604052" +// + "8093929190818152602001838380828437600081840152601f19601f820116905080830192505050" +// + "50505050919291929050505061022f565b005b600081838587da9050949350505050565b808284db" +// + "5050505056fea26474726f6e582071af66a376cfd560797ad3c889d08b9037d8ec121805b96fd252" +// + "3415b77f4df264736f6c637828302e352e31332d646576656c6f702e323032302e382e31332b636f" +// + "6d6d69742e37633236393863300057"; +// long value = 0; +// long fee = 100000000; +// long consumeUserResourcePercent = 0; +// // deploy contract +// Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, +// null); +// byte[] factoryAddress = WalletUtil.generateContractAddress(trx); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); +// Assert.assertNull(runtime.getRuntimeError()); +// +// // Trigger contract method: getContractAddress() +// String methodByAddr = "getContractAddress()"; +// String hexInput = AbiUtil.parseMethod(methodByAddr, Collections.emptyList()); +// TVMTestResult result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// byte[] returnValue = result.getRuntime().getResult().getHReturn(); +// +// // Contract A Address +// String tmpAddress = "a0" + Hex.toHexString(returnValue).substring(24); +// +// // sendcoin to A address 100000000000 +// rootRepository.addBalance(ByteArray.fromHexString(tmpAddress), 10000000000L); +// rootRepository.commit(); +// Assert.assertEquals(rootRepository.getBalance(ByteArray.fromHexString(tmpAddress)), +// 10000000000L); +// +// // assetissue test +// String tokenP1 = "74657374"; +// long tokenP3 = 1000; +// long tokenP4 = 2; +// String methodTokenIssue = "TokenIssue(bytes32,bytes32,uint64,uint8)"; +// hexInput = AbiUtil.parseMethod(methodTokenIssue, Arrays.asList(tokenP1, tokenP1, tokenP3, +// tokenP4)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertEquals(ByteArray.toInt(result.getRuntime().getResult().getHReturn()), +// 1000001); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// +// // updateasset test +// String methodUpdateAsset = "UpdateAsset(trcToken,string,string)"; +// // 1,abc,abc, +// long updateP1 = 1000001; +// String updateP2 = "abc"; +// hexInput = AbiUtil.parseMethod(methodUpdateAsset, +// Arrays.asList(updateP1, updateP2, updateP2)); +// result = TvmTestUtils.triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, +// Hex.decode(hexInput), value, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() +// .get(0).getUrl().toByteArray()), +// "abc"); +// Assert.assertEquals(ByteArray.toStr(manager.getAssetIssueV2Store().getAllAssetIssues() +// .get(0).getDesc().toByteArray()), +// "abc"); +// } +//} +// +// +// diff --git a/framework/src/test/java/org/tron/common/runtime/vm/UnStakeTest.java b/framework/src/test/java/org/tron/common/runtime/vm/UnStakeTest.java new file mode 100644 index 00000000000..c25291b24e9 --- /dev/null +++ b/framework/src/test/java/org/tron/common/runtime/vm/UnStakeTest.java @@ -0,0 +1,133 @@ +//package org.tron.common.runtime.vm; +// +//import java.util.Arrays; +//import java.util.Collections; +//import lombok.extern.slf4j.Slf4j; +//import org.junit.Test; +//import org.spongycastle.util.encoders.Hex; +//import org.testng.Assert; +//import org.tron.common.runtime.TVMTestResult; +//import org.tron.common.runtime.TvmTestUtils; +//import org.tron.common.utils.WalletUtil; +//import org.tron.core.exception.ContractExeException; +//import org.tron.core.exception.ContractValidateException; +//import org.tron.core.exception.ReceiptCheckErrException; +//import org.tron.core.exception.VMIllegalException; +//import org.tron.core.vm.config.ConfigLoader; +//import org.tron.core.vm.config.VMConfig; +//import org.tron.protos.Protocol; +//import stest.tron.wallet.common.client.utils.AbiUtil; +// +//@Slf4j +//public class UnStakeTest extends VMContractTestBase { +// +// /*pragma solidity ^0.5.0; +// contract HelloWorld{ +// function stakeTest(address sr, uint256 amount) public returns (bool) { +// return stake(sr, amount); +// } +// function unstakeTest() public public returns (bool) { +// return unstake(); +// } +// function withdrawRewardTest() public returns (uint) { +// return withdrawreward(); +// } +// function rewardBalanceTest(address addr) public returns (uint) { +// return addr.rewardbalance; +// } +// }*/ +// +// @Test +// public void testUnstake() throws ContractExeException, +// ReceiptCheckErrException, VMIllegalException, +// ContractValidateException { +// ConfigLoader.disable = true; +// VMConfig.initAllowTvmTransferTrc10(1); +// VMConfig.initAllowTvmConstantinople(1); +// VMConfig.initAllowTvmSolidity059(1); +// VMConfig.initAllowTvmStake(1); +// manager.getDynamicPropertiesStore().saveChangeDelegation(1); +// String contractName = "unstakeTest"; +// byte[] address = Hex.decode(OWNER_ADDRESS); +// String abi = "[{\"constant\":false,\"inputs\":[{\"internalType\":\"address\"," +// + "\"name\":\"addr\"," +// + "\"type\":\"address\"}],\"name\":\"rewardBalanceTest\"," +// + "\"outputs\":[{\"internalType\":\"uint256\"," +// + "\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false," +// + "\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\" +// :\"address\"," +// + "\"name\":\"sr\",\"type\":\"address\"},{\"internalType\":\"uint256\", +// \"name\":\"amount\"," +// + "\"type\":\"uint256\"}],\"name\":\"stakeTest\",\"outputs\":[{\"internalType\" +// :\"bool\"," +// + "\"name\":\"\"," +// + "\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\"," +// + "\"type\":\"function\"}," +// + "{\"constant\":false,\"inputs\":[],\"name\":\"unstakeTest\"," +// + "\"outputs\":[{\"internalType\":\"bool\"," +// + "\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\": +// \"nonpayable\"," +// + "\"type\":\"function\"},{\"constant\":false,\"inputs\":[]," +// + "\"name\":\"withdrawRewardTest\"," +// + "\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}]," +// + "\"payable\":false," +// + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"; +// String factoryCode = +// "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a576000" +// + "80fd5b506102018061003a6000396000f3fe608060405234801561001057600080fd5b50d3801561" +// + "001d57600080fd5b50d2801561002a57600080fd5b50600436106100665760003560e01c8063a223" +// + "c65f1461006b578063b3e835e1146100c3578063c290120a146100e5578063e49de2d01461010357" +// + "5b600080fd5b6100ad6004803603602081101561008157600080fd5b81019080803573ffffffffff" +// + "ffffffffffffffffffffffffffffff169060200190929190505050610169565b6040518082815260" +// + "200191505060405180910390f35b6100cb61018a565b604051808215151515815260200191505060" +// + "405180910390f35b6100ed610192565b6040518082815260200191505060405180910390f35b6101" +// + "4f6004803603604081101561011957600080fd5b81019080803573ffffffffffffffffffffffffff" +// + "ffffffffffffff1690602001909291908035906020019092919050505061019a565b604051808215" +// + "151515815260200191505060405180910390f35b60008173ffffffffffffffffffffffffffffffff" +// + "ffffffff16d89050919050565b6000d6905090565b6000d7905090565b60008183d5905092915050" +// + "56fea26474726f6e58204ba2e62e49bd76cb49dd0e1ce7be45dcae5f764ea02b1a11a34c7ef83ca3" +// + "362764736f6c637828302e352e31332d646576656c6f702e323032302e382e31332b636f6d6d6974" +// + "2e37633236393863300057"; +// long value = 0; +// long fee = 100000000; +// long consumeUserResourcePercent = 0; +// // deploy contract +// Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( +// contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, +// null); +// byte[] factoryAddress = WalletUtil.generateContractAddress(trx); +// runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, manager, null); +// Assert.assertNull(runtime.getRuntimeError()); +// +// rootRepository.addBalance(factoryAddress, 10000000000L); +// rootRepository.commit(); +// Assert.assertEquals(rootRepository.getBalance(factoryAddress), 10000000000L); +// +// manager.getDynamicPropertiesStore().saveMinFrozenTime(0); +// +// // Trigger contract method: stakeTest(address,uint256) +// String stakeTest = "stakeTest(address,uint256)"; +// String witness = "27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1"; +// String hexInput = AbiUtil.parseMethod(stakeTest, Arrays.asList(witness, 100000000)); +// TVMTestResult result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// byte[] returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000001"); +// +// //vote +// String unstakeTest = "unstakeTest()"; +// hexInput = AbiUtil.parseMethod(unstakeTest, Collections.emptyList()); +// result = TvmTestUtils +// .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), +// factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); +// Assert.assertNull(result.getRuntime().getRuntimeError()); +// returnValue = result.getRuntime().getResult().getHReturn(); +// Assert.assertEquals(Hex.toHexString(returnValue), +// "0000000000000000000000000000000000000000000000000000000000000001"); +// } +// +//} diff --git a/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java b/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java index 777166a0bc0..f6da2c60bff 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java @@ -26,7 +26,6 @@ @Slf4j public class VMContractTestBase { - protected String dbPath; protected Runtime runtime; protected Manager manager; From af36474b67073e9a60cda2daf6b52cd172bc808f Mon Sep 17 00:00:00 2001 From: liukai Date: Tue, 21 Dec 2021 15:52:08 +0800 Subject: [PATCH 50/60] modify BlockVersion 1. upgrade Version to 4.4.3 --- framework/src/main/java/org/tron/program/Version.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/framework/src/main/java/org/tron/program/Version.java b/framework/src/main/java/org/tron/program/Version.java index 19a8c5d67c7..d6b9682b4b7 100644 --- a/framework/src/main/java/org/tron/program/Version.java +++ b/framework/src/main/java/org/tron/program/Version.java @@ -4,7 +4,7 @@ public class Version { public static final String VERSION_NAME = "GreatVoyage-v4.4.1-239-g269ed47a7"; public static final String VERSION_CODE = "16580"; - private static final String VERSION = "4.4.2"; + private static final String VERSION = "4.4.3"; public static String getVersion() { return VERSION; From 568b5e0bd71a1ca5e9d1c738f5d668c80eaabedb Mon Sep 17 00:00:00 2001 From: forfreeday Date: Thu, 19 Jan 2023 11:34:16 +0800 Subject: [PATCH 51/60] feature(version): update VERSION --- framework/src/main/java/org/tron/program/Version.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/framework/src/main/java/org/tron/program/Version.java b/framework/src/main/java/org/tron/program/Version.java index e44555bff65..f48fe70d882 100644 --- a/framework/src/main/java/org/tron/program/Version.java +++ b/framework/src/main/java/org/tron/program/Version.java @@ -2,8 +2,8 @@ public class Version { - public static final String VERSION_NAME = "GreatVoyage-v4.5.2-125-ga2906563d"; - public static final String VERSION_CODE = "17198"; + public static final String VERSION_NAME = "GreatVoyage-v4.6.0-385-g4445a420c"; + public static final String VERSION_CODE = "17585"; private static final String VERSION = "4.7.0"; public static String getVersion() { From 02e62b2802e2ef2569ebebeb56e2e6c07fb7cc05 Mon Sep 17 00:00:00 2001 From: YAaron Date: Fri, 18 Aug 2023 11:00:19 +0800 Subject: [PATCH 52/60] open the participation logic (#5435) --- .../src/main/java/org/tron/consensus/dpos/StateManager.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/consensus/src/main/java/org/tron/consensus/dpos/StateManager.java b/consensus/src/main/java/org/tron/consensus/dpos/StateManager.java index 99e44166ca1..19d1f88a243 100644 --- a/consensus/src/main/java/org/tron/consensus/dpos/StateManager.java +++ b/consensus/src/main/java/org/tron/consensus/dpos/StateManager.java @@ -51,14 +51,13 @@ public State getState() { return State.DUP_WITNESS; } - /*int participation = consensusDelegate.calculateFilledSlotsCount(); + int participation = consensusDelegate.calculateFilledSlotsCount(); int minParticipationRate = dposService.getMinParticipationRate(); if (participation < minParticipationRate) { logger .warn("Participation:{} < minParticipationRate:{}", participation, minParticipationRate); return State.LOW_PARTICIPATION; } - */ return State.OK; } From d8967152db039d5ee6860f680d4ec468e1ac2348 Mon Sep 17 00:00:00 2001 From: liukai Date: Mon, 16 Oct 2023 20:38:53 +0800 Subject: [PATCH 53/60] test(case): modify output dir --- .../common/runtime/vm/VMContractTestBase.java | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java b/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java index f6da2c60bff..ee49bdca7f6 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java @@ -1,13 +1,14 @@ package org.tron.common.runtime.vm; -import java.io.File; +import java.io.IOException; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; import org.junit.After; import org.junit.Before; +import org.junit.Rule; +import org.junit.rules.TemporaryFolder; import org.tron.common.application.TronApplicationContext; import org.tron.common.runtime.Runtime; -import org.tron.common.utils.FileUtil; import org.tron.consensus.dpos.DposSlot; import org.tron.consensus.dpos.MaintenanceManager; import org.tron.core.ChainBaseManager; @@ -26,7 +27,8 @@ @Slf4j public class VMContractTestBase { - protected String dbPath; + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); protected Runtime runtime; protected Manager manager; protected Repository rootRepository; @@ -49,9 +51,9 @@ public class VMContractTestBase { } @Before - public void init() { - dbPath = "output_" + this.getClass().getName(); - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); + public void init() throws IOException { + Args.setParam(new String[]{"--output-directory", + temporaryFolder.newFolder().toString(), "--debug"}, Constant.TEST_CONF); context = new TronApplicationContext(DefaultConfig.class); // TRdmP9bYvML7dGUX9Rbw2kZrE2TayPZmZX - 41abd4b9367799eaa3197fecb144eb71de1e049abc @@ -76,10 +78,5 @@ public void init() { public void destroy() { Args.clearParam(); context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.error("Release resources failure."); - } } } From cd439500b4fd642ef171f2a588e3a589c594ea8c Mon Sep 17 00:00:00 2001 From: liukai Date: Thu, 7 Dec 2023 22:06:29 +0800 Subject: [PATCH 54/60] feat(config): add a terminator --- framework/src/main/resources/config.conf | 1 + 1 file changed, 1 insertion(+) diff --git a/framework/src/main/resources/config.conf b/framework/src/main/resources/config.conf index 91f108b74a9..e357267a4ae 100644 --- a/framework/src/main/resources/config.conf +++ b/framework/src/main/resources/config.conf @@ -662,3 +662,4 @@ event.subscribe = { } } + From 4ef39b9054546cc841c01875812d67f269744488 Mon Sep 17 00:00:00 2001 From: liukai Date: Mon, 11 Mar 2024 17:10:31 +0800 Subject: [PATCH 55/60] feat(Nile): resolve conflict --- .../main/java/org/tron/program/Version.java | 6 +-- .../java/org/tron/core/db/ManagerTest.java | 46 ++++++++++++++++--- 2 files changed, 42 insertions(+), 10 deletions(-) diff --git a/framework/src/main/java/org/tron/program/Version.java b/framework/src/main/java/org/tron/program/Version.java index 74400376acd..6f26752524c 100644 --- a/framework/src/main/java/org/tron/program/Version.java +++ b/framework/src/main/java/org/tron/program/Version.java @@ -2,9 +2,9 @@ public class Version { - public static final String VERSION_NAME = "GreatVoyage-v4.7.2-140-g9d13f9cb69"; - public static final String VERSION_CODE = "18173"; - private static final String VERSION = "4.7.3.1"; + public static final String VERSION_NAME = "GreatVoyage-v4.7.3-5-g788136ebe"; + public static final String VERSION_CODE = "18180"; + private static final String VERSION = "4.7.4"; public static String getVersion() { return VERSION; diff --git a/framework/src/test/java/org/tron/core/db/ManagerTest.java b/framework/src/test/java/org/tron/core/db/ManagerTest.java index bd79f7d9776..34a227aee8c 100755 --- a/framework/src/test/java/org/tron/core/db/ManagerTest.java +++ b/framework/src/test/java/org/tron/core/db/ManagerTest.java @@ -580,11 +580,19 @@ public void pushSwitchFork() TaposException, ReceiptCheckErrException, TooBigTransactionException, AccountResourceInsufficientException, EventBloomException { - String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; - String key2 = "c85ef7d79691fe79573b1a7064c19c1a9819ebdbd1faaab1a8ec92344438aaf4"; + String key = PublicMethod.getRandomPrivateKey(); + String key2 = PublicMethod.getRandomPrivateKey(); byte[] privateKey = ByteArray.fromHexString(key); final ECKey ecKey = ECKey.fromPrivate(privateKey); byte[] address = ecKey.getAddress(); + + ByteString addressByte = ByteString.copyFrom(address); + AccountCapsule accountCapsule = + new AccountCapsule(Protocol.Account.newBuilder() + .setAddress(addressByte).build()); + chainManager.getAccountStore() + .put(addressByte.toByteArray(), accountCapsule); + WitnessCapsule sr1 = new WitnessCapsule( ByteString.copyFrom(address), "www.tron.net/first"); sr1.setVoteCount(1000000000L); @@ -703,13 +711,23 @@ public void fork() Args.setParam(new String[]{"--witness"}, Constant.TEST_CONF); long size = chainManager.getBlockStore().size(); // System.out.print("block store size:" + size + "\n"); - String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; + String key = PublicMethod.getRandomPrivateKey(); byte[] privateKey = ByteArray.fromHexString(key); final ECKey ecKey = ECKey.fromPrivate(privateKey); byte[] address = ecKey.getAddress(); + + ByteString addressByte = ByteString.copyFrom(address); + AccountCapsule accountCapsule = + new AccountCapsule(Protocol.Account.newBuilder() + .setAddress(addressByte).build()); + chainManager.getAccountStore() + .put(addressByte.toByteArray(), accountCapsule); + + WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(address)); chainManager.getWitnessScheduleStore().saveActiveWitnesses(new ArrayList<>()); chainManager.addWitness(ByteString.copyFrom(address)); + chainManager.getWitnessStore().put(address, witnessCapsule); Block block = getSignedBlock(witnessCapsule.getAddress(), 1533529947843L, privateKey); @@ -822,14 +840,20 @@ public void doNotSwitch() Args.setParam(new String[]{"--witness"}, Constant.TEST_CONF); long size = chainManager.getBlockStore().size(); System.out.print("block store size:" + size + "\n"); - String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; + String key = PublicMethod.getRandomPrivateKey(); byte[] privateKey = ByteArray.fromHexString(key); final ECKey ecKey = ECKey.fromPrivate(privateKey); byte[] address = ecKey.getAddress(); - + ByteString addressByte = ByteString.copyFrom(address); + AccountCapsule accountCapsule = + new AccountCapsule(Protocol.Account.newBuilder() + .setAddress(addressByte).build()); + chainManager.getAccountStore() + .put(addressByte.toByteArray(), accountCapsule); WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(address)); chainManager.getWitnessScheduleStore().saveActiveWitnesses(new ArrayList<>()); chainManager.addWitness(ByteString.copyFrom(address)); + chainManager.getWitnessStore().put(address, witnessCapsule); Block block = getSignedBlock(witnessCapsule.getAddress(), 1533529947843L, privateKey); dbManager.pushBlock(new BlockCapsule(block)); @@ -928,14 +952,22 @@ public void switchBack() Args.setParam(new String[]{"--witness"}, Constant.TEST_CONF); long size = chainManager.getBlockStore().size(); System.out.print("block store size:" + size + "\n"); - String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; + String key = PublicMethod.getRandomPrivateKey();; byte[] privateKey = ByteArray.fromHexString(key); final ECKey ecKey = ECKey.fromPrivate(privateKey); byte[] address = ecKey.getAddress(); + + ByteString addressByte = ByteString.copyFrom(address); + AccountCapsule accountCapsule = + new AccountCapsule(Protocol.Account.newBuilder() + .setAddress(addressByte).build()); + chainManager.getAccountStore() + .put(addressByte.toByteArray(), accountCapsule); + WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(address)); chainManager.getWitnessScheduleStore().saveActiveWitnesses(new ArrayList<>()); chainManager.addWitness(ByteString.copyFrom(address)); - + chainManager.getWitnessStore().put(address, witnessCapsule); Block block = getSignedBlock(witnessCapsule.getAddress(), 1533529947843L, privateKey); dbManager.pushBlock(new BlockCapsule(block)); From 7c561852cee7feb86feaa0776e59c0285c00bea8 Mon Sep 17 00:00:00 2001 From: Kayle Date: Mon, 11 Mar 2024 17:50:01 +0800 Subject: [PATCH 56/60] feat(Nile): add a blank line --- framework/src/test/java/org/tron/core/db/ManagerTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/framework/src/test/java/org/tron/core/db/ManagerTest.java b/framework/src/test/java/org/tron/core/db/ManagerTest.java index 34a227aee8c..ff40d6a9eb6 100755 --- a/framework/src/test/java/org/tron/core/db/ManagerTest.java +++ b/framework/src/test/java/org/tron/core/db/ManagerTest.java @@ -596,6 +596,8 @@ public void pushSwitchFork() WitnessCapsule sr1 = new WitnessCapsule( ByteString.copyFrom(address), "www.tron.net/first"); sr1.setVoteCount(1000000000L); + + byte[] privateKey2 = ByteArray.fromHexString(key2); final ECKey ecKey2 = ECKey.fromPrivate(privateKey2); byte[] address2 = ecKey2.getAddress(); From 0b719116895bc127dd880bd79300aceca36cf1b6 Mon Sep 17 00:00:00 2001 From: Kayle Date: Mon, 11 Mar 2024 17:54:53 +0800 Subject: [PATCH 57/60] feat(): remove indentation --- framework/src/test/java/org/tron/core/db/ManagerTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/framework/src/test/java/org/tron/core/db/ManagerTest.java b/framework/src/test/java/org/tron/core/db/ManagerTest.java index ff40d6a9eb6..053647cc25a 100755 --- a/framework/src/test/java/org/tron/core/db/ManagerTest.java +++ b/framework/src/test/java/org/tron/core/db/ManagerTest.java @@ -597,7 +597,7 @@ public void pushSwitchFork() ByteString.copyFrom(address), "www.tron.net/first"); sr1.setVoteCount(1000000000L); - + byte[] privateKey2 = ByteArray.fromHexString(key2); final ECKey ecKey2 = ECKey.fromPrivate(privateKey2); byte[] address2 = ecKey2.getAddress(); From 71e9c124f1a09b83847350b557007ce06ca7913f Mon Sep 17 00:00:00 2001 From: halibobo1205 <82020050+halibobo1205@users.noreply.github.com> Date: Mon, 11 Mar 2024 19:09:23 +0800 Subject: [PATCH 58/60] Revert "feat(Nile): merge release_v4.7.4 into Nile" --- README.md | 141 ++-- Tron protobuf protocol document.md | 16 +- actuator/build.gradle | 16 + .../org/tron/core/utils/ProposalUtil.java | 23 +- build.gradle | 13 +- chainbase/build.gradle | 34 +- .../org/tron/common/utils/ForkController.java | 2 +- .../tron/core/capsule/TransactionCapsule.java | 4 +- .../tron/core/capsule/utils/MerkleTree.java | 2 - .../core/db/common/iterator/DBIterator.java | 64 +- .../db/common/iterator/RockStoreIterator.java | 64 +- .../db/common/iterator/StoreIterator.java | 61 +- .../tron/core/service/MortgageService.java | 45 +- .../tron/core/service/RewardViCalService.java | 286 -------- .../core/store/DynamicPropertiesStore.java | 17 - .../org/tron/core/store/RewardViStore.java | 43 -- common/build.gradle | 9 +- .../common/parameter/CommonParameter.java | 17 +- .../org/tron/common/utils/MerkleRoot.java | 68 -- .../src/main/java/org/tron/core/Constant.java | 9 +- .../java/org/tron/core/config/Parameter.java | 5 +- .../org/tron/core/config/args/Storage.java | 19 - config/checkstyle/checkStyle.xml | 2 +- config/checkstyle/checkStyleAll.xml | 2 +- consensus/build.gradle | 13 + .../consensus/pbft/PbftMessageHandle.java | 4 +- crypto/build.gradle | 2 + docs/implement-a-customized-actuator-en.md | 2 +- docs/implement-a-customized-actuator-zh.md | 2 +- framework/build.gradle | 33 +- framework/config/checkstyle/checkStyle.xml | 2 +- framework/config/checkstyle/checkStyleAll.xml | 2 +- .../common/application/ApplicationImpl.java | 4 +- .../nativequeue/NativeMessageQueue.java | 6 +- .../src/main/java/org/tron/core/Wallet.java | 15 - .../java/org/tron/core/config/args/Args.java | 58 +- .../tron/core/consensus/ProposalService.java | 4 - .../main/java/org/tron/core/db/Manager.java | 10 - .../db/common/iterator/AbstractIterator.java | 41 ++ .../common/iterator/AssetIssueIterator.java | 17 + .../core/db/common/iterator/DBIterator.java | 9 + .../common/iterator/TransactionIterator.java | 22 + .../db/common/iterator/WitnessIterator.java | 17 + .../org/tron/core/net/TronNetDelegate.java | 15 - .../net/message/handshake/HelloMessage.java | 29 +- .../net/messagehandler/BlockMsgHandler.java | 16 +- .../messagehandler/InventoryMsgHandler.java | 7 - .../messagehandler/PbftDataSyncHandler.java | 18 +- .../net/messagehandler/PbftMsgHandler.java | 3 - .../tron/core/net/peer/PeerConnection.java | 1 + .../service/handshake/HandshakeService.java | 15 +- .../tron/core/services/NodeInfoService.java | 2 +- .../org/tron/core/services/RpcApiService.java | 18 +- .../org/tron/core/services/http/Util.java | 2 +- .../interfaceOnPBFT/RpcApiServiceOnPBFT.java | 5 - .../RpcApiServiceOnSolidity.java | 5 - .../org/tron/tool/litefullnode/DbTool.java | 199 ++++++ .../tool/litefullnode/LiteFullNodeTool.java | 637 ++++++++++++++++++ .../java/org/tron/tool/litefullnode/README.md | 109 +++ .../java/org/tron/tool/litefullnode/Util.java | 62 ++ .../tool/litefullnode/db/DBInterface.java | 21 + .../tool/litefullnode/db/LevelDBImpl.java | 46 ++ .../tool/litefullnode/db/RocksDBImpl.java | 66 ++ .../litefullnode/iterator/DBIterator.java | 18 + .../iterator/LevelDBIterator.java | 47 ++ .../litefullnode/iterator/RockDBIterator.java | 48 ++ .../src/main/resources/config-backup.conf | 1 + framework/src/main/resources/config-beta.conf | 1 + .../src/main/resources/config-localtest.conf | 4 +- .../src/main/resources/config-test-net.conf | 1 + framework/src/main/resources/config.conf | 13 +- .../org/tron/common/config/args/ArgsTest.java | 1 - .../tron/common/jetty/JettyServerTest.java | 63 -- .../core/actuator/ActuatorFactoryTest.java | 71 -- .../core/actuator/utils/ProposalUtilTest.java | 57 +- .../actuator/utils/TransactionUtilTest.java | 19 - .../core/capsule/utils/DecodeResultTest.java | 28 - .../core/capsule/utils/MerkleTreeTest.java | 35 +- .../tron/core/capsule/utils/RLPListTest.java | 81 --- .../org/tron/core/config/args/ArgsTest.java | 32 +- .../tron/core/db/AccountTraceStoreTest.java | 13 - .../org/tron/core/db/BlockIndexStoreTest.java | 64 -- .../java/org/tron/core/db/BlockStoreTest.java | 69 -- .../java/org/tron/core/db/DBIteratorTest.java | 110 +-- .../core/db/DelegatedResourceStoreTest.java | 15 - .../org/tron/core/db/DelegationStoreTest.java | 17 - .../org/tron/core/db/ExchangeStoreTest.java | 25 - .../org/tron/core/db/ExchangeV2StoreTest.java | 26 - .../tron/core/db/MarketAccountStoreTest.java | 16 - .../tron/core/db/MarketOrderStoreTest.java | 17 - .../tron/core/db/RecentBlockStoreTest.java | 81 --- .../core/db/RecentTransactionStoreTest.java | 72 -- .../tron/core/db/TransactionHistoryTest.java | 7 - .../tron/core/db/TransactionStoreTest.java | 2 +- .../org/tron/core/db/ZKProofStoreTest.java | 58 -- .../tron/core/net/TronNetDelegateTest.java | 52 -- .../InventoryMsgHandlerTest.java | 22 +- .../PbftDataSyncHandlerTest.java | 7 +- .../messagehandler/PbftMsgHandlerTest.java | 9 - .../net/services/HandShakeServiceTest.java | 45 -- .../net/services/TronStatsManagerTest.java | 27 - .../java/org/tron/core/pbft/PbftTest.java | 1 - .../tron/core/services/ComputeRewardTest.java | 307 --------- .../core/services/RpcApiServicesTest.java | 6 +- .../LiteFnQueryGrpcInterceptorTest.java | 6 +- .../filter/RpcApiAccessInterceptorTest.java | 6 +- .../services/http/ClearABIServletTest.java | 92 --- .../http/CreateAccountServletTest.java | 75 --- .../http/CreateAssetIssueServletTest.java | 90 --- .../http/CreateSpendAuthSigServletTest.java | 60 -- .../http/CreateWitnessServletTest.java | 88 --- .../http/GetAccountByIdServletTest.java | 47 -- .../http/GetBlockByIdServletTest.java | 51 -- .../http/GetBlockByNumServletTest.java | 69 -- ...tTransactionInfoByBlockNumServletTest.java | 79 --- .../GetTransactionInfoByIdServletTest.java | 126 ---- ...TransactionListFromPendingServletTest.java | 38 -- .../http/UpdateAccountServletTest.java | 77 --- .../services/jsonrpc/BlockResultTest.java | 46 -- .../services/jsonrpc/BuildArgumentsTest.java | 73 -- .../services/jsonrpc/CallArgumentsTest.java | 47 -- .../jsonrpc/TransactionReceiptTest.java | 66 -- .../jsonrpc/TransactionResultTest.java | 59 -- .../tron/core/zksnark/NoteEncDecryTest.java | 2 + .../core/zksnark/ShieldedReceiveTest.java | 5 +- .../tron/program/LiteFullNodeToolTest.java | 202 ++++++ framework/src/test/resources/args-test.conf | 224 ------ .../src/test/resources/config-localtest.conf | 14 +- .../test/resources/config-test-dbbackup.conf | 1 + .../src/test/resources/config-test-index.conf | 1 + .../test/resources/config-test-mainnet.conf | 1 + .../resources/config-test-storagetest.conf | 3 +- framework/src/test/resources/config-test.conf | 10 +- plugins/README.md | 12 +- plugins/build.gradle | 3 + .../src/main/java/org/tron/plugins/Db.java | 3 +- .../main/java/org/tron/plugins/DbRoot.java | 121 ---- .../org/tron/plugins/utils/MerkleRoot.java | 68 -- .../org/tron/plugins/utils/Sha256Hash.java | 10 +- .../tron/plugins/utils/db/DBInterface.java | 2 - .../org/tron/plugins/utils/db/DbTool.java | 18 +- .../tron/plugins/utils/db/LevelDBImpl.java | 7 +- .../tron/plugins/utils/db/RocksDBImpl.java | 7 +- .../java/org/tron/plugins/DbLiteTest.java | 6 +- .../java/org/tron/plugins/DbRootTest.java | 82 --- protocol/build.gradle | 2 - protocol/src/main/protos/api/api.proto | 2 - protocol/src/main/protos/core/Tron.proto | 1 - quickstart.md | 20 + run.md | 10 +- script/checkStyle.sh | 26 + script/codecov.sh | 5 + script/querySonar.sh | 41 ++ script/sonar.sh | 89 +++ 154 files changed, 2141 insertions(+), 4141 deletions(-) delete mode 100644 chainbase/src/main/java/org/tron/core/service/RewardViCalService.java delete mode 100755 chainbase/src/main/java/org/tron/core/store/RewardViStore.java delete mode 100644 common/src/main/java/org/tron/common/utils/MerkleRoot.java create mode 100644 framework/src/main/java/org/tron/core/db/common/iterator/AbstractIterator.java create mode 100644 framework/src/main/java/org/tron/core/db/common/iterator/AssetIssueIterator.java create mode 100755 framework/src/main/java/org/tron/core/db/common/iterator/DBIterator.java create mode 100644 framework/src/main/java/org/tron/core/db/common/iterator/TransactionIterator.java create mode 100644 framework/src/main/java/org/tron/core/db/common/iterator/WitnessIterator.java create mode 100644 framework/src/main/java/org/tron/tool/litefullnode/DbTool.java create mode 100644 framework/src/main/java/org/tron/tool/litefullnode/LiteFullNodeTool.java create mode 100644 framework/src/main/java/org/tron/tool/litefullnode/README.md create mode 100644 framework/src/main/java/org/tron/tool/litefullnode/Util.java create mode 100644 framework/src/main/java/org/tron/tool/litefullnode/db/DBInterface.java create mode 100644 framework/src/main/java/org/tron/tool/litefullnode/db/LevelDBImpl.java create mode 100644 framework/src/main/java/org/tron/tool/litefullnode/db/RocksDBImpl.java create mode 100644 framework/src/main/java/org/tron/tool/litefullnode/iterator/DBIterator.java create mode 100644 framework/src/main/java/org/tron/tool/litefullnode/iterator/LevelDBIterator.java create mode 100644 framework/src/main/java/org/tron/tool/litefullnode/iterator/RockDBIterator.java delete mode 100644 framework/src/test/java/org/tron/common/jetty/JettyServerTest.java delete mode 100644 framework/src/test/java/org/tron/core/actuator/ActuatorFactoryTest.java delete mode 100644 framework/src/test/java/org/tron/core/capsule/utils/DecodeResultTest.java delete mode 100644 framework/src/test/java/org/tron/core/capsule/utils/RLPListTest.java delete mode 100644 framework/src/test/java/org/tron/core/db/BlockIndexStoreTest.java delete mode 100644 framework/src/test/java/org/tron/core/db/RecentBlockStoreTest.java delete mode 100644 framework/src/test/java/org/tron/core/db/RecentTransactionStoreTest.java delete mode 100644 framework/src/test/java/org/tron/core/db/ZKProofStoreTest.java delete mode 100644 framework/src/test/java/org/tron/core/net/TronNetDelegateTest.java delete mode 100644 framework/src/test/java/org/tron/core/net/services/TronStatsManagerTest.java delete mode 100644 framework/src/test/java/org/tron/core/services/ComputeRewardTest.java delete mode 100644 framework/src/test/java/org/tron/core/services/http/ClearABIServletTest.java delete mode 100644 framework/src/test/java/org/tron/core/services/http/CreateAccountServletTest.java delete mode 100644 framework/src/test/java/org/tron/core/services/http/CreateAssetIssueServletTest.java delete mode 100644 framework/src/test/java/org/tron/core/services/http/CreateSpendAuthSigServletTest.java delete mode 100644 framework/src/test/java/org/tron/core/services/http/CreateWitnessServletTest.java delete mode 100644 framework/src/test/java/org/tron/core/services/http/GetAccountByIdServletTest.java delete mode 100644 framework/src/test/java/org/tron/core/services/http/GetBlockByIdServletTest.java delete mode 100644 framework/src/test/java/org/tron/core/services/http/GetBlockByNumServletTest.java delete mode 100644 framework/src/test/java/org/tron/core/services/http/GetTransactionInfoByBlockNumServletTest.java delete mode 100644 framework/src/test/java/org/tron/core/services/http/GetTransactionInfoByIdServletTest.java delete mode 100644 framework/src/test/java/org/tron/core/services/http/GetTransactionListFromPendingServletTest.java delete mode 100644 framework/src/test/java/org/tron/core/services/http/UpdateAccountServletTest.java delete mode 100644 framework/src/test/java/org/tron/core/services/jsonrpc/BlockResultTest.java delete mode 100644 framework/src/test/java/org/tron/core/services/jsonrpc/BuildArgumentsTest.java delete mode 100644 framework/src/test/java/org/tron/core/services/jsonrpc/CallArgumentsTest.java delete mode 100644 framework/src/test/java/org/tron/core/services/jsonrpc/TransactionReceiptTest.java delete mode 100644 framework/src/test/java/org/tron/core/services/jsonrpc/TransactionResultTest.java create mode 100644 framework/src/test/java/org/tron/program/LiteFullNodeToolTest.java delete mode 100644 framework/src/test/resources/args-test.conf delete mode 100644 plugins/src/main/java/org/tron/plugins/DbRoot.java delete mode 100644 plugins/src/main/java/org/tron/plugins/utils/MerkleRoot.java delete mode 100644 plugins/src/test/java/org/tron/plugins/DbRootTest.java create mode 100644 script/checkStyle.sh create mode 100644 script/codecov.sh create mode 100644 script/querySonar.sh create mode 100644 script/sonar.sh diff --git a/README.md b/README.md index 89101bbc4d1..4d1d7b0b3b6 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ Java implementation of the Tron Protocol +

@@ -41,7 +42,6 @@

## Table of Contents - - [What’s TRON?](#whats-tron) - [Building the Source Code](#building-the-source) - [Running java-tron](#running-java-tron) @@ -55,109 +55,94 @@ TRON is a project dedicated to building the infrastructure for a truly decentralized Internet. -- Tron Protocol, one of the largest blockchain-based operating systems in the world, offers scalable, high-availability and high-throughput support that underlies all the decentralized applications in the TRON ecosystem. +* Tron Protocol, one of the largest blockchain-based operating systems in the world, offers scalable, high-availability and high-throughput support that underlies all the decentralized applications in the TRON ecosystem. -- Tron Virtual Machine (TVM) allows anyone to develop decentralized applications (DAPPs) for themselves or their communities with smart contracts thereby making decentralized crowdfunding and token issuance easier than ever. +* Tron Virtual Machine (TVM) allows anyone to develop decentralized applications (DAPPs) for themselves or their communities with smart contracts thereby making decentralized crowdfunding and token issuance easier than ever. TRON enables large-scale development and engagement. With over 2000 transactions per second (TPS), high concurrency, low latency, and massive data transmission. It is ideal for building decentralized entertainment applications. Free features and incentive systems allow developers to create premium app experiences for users. # Building the source - Building java-tron requires `git` and 64-bit version of `Oracle JDK 1.8` to be installed, other JDK versions are not supported yet. Make sure you operate on `Linux` and `MacOS` operating systems. Clone the repo and switch to the `master` branch -```bash -$ git clone https://github.com/tronprotocol/java-tron.git -$ cd java-tron -$ git checkout -t origin/master -``` - + ```bash + $ git clone https://github.com/tronprotocol/java-tron.git + $ cd java-tron + $ git checkout -t origin/master + ``` then run the following command to build java-tron, the `FullNode.jar` file can be found in `java-tron/build/libs/` after build successful. - ```bash $ ./gradlew clean build -x test ``` -# Running java-tron +# Running java-tron Running java-tron requires 64-bit version of `Oracle JDK 1.8` to be installed, other JDK versions are not supported yet. Make sure you operate on `Linux` and `MacOS` operating systems. -Get the mainnet configuration file: [main_net_config.conf](https://github.com/tronprotocol/tron-deployment/blob/master/main_net_config.conf), other network configuration files can be found [here](https://github.com/tronprotocol/tron-deployment). - +Get the mainnet configuration file: [main_net_config.conf](https://github.com/tronprotocol/tron-deployment/blob/master/main_net_config.conf), other network configuration files can be find [here](https://github.com/tronprotocol/tron-deployment). ## Hardware Requirements - Minimum: - -- CPU with 8 cores -- 16GB RAM -- 2TB free storage space to sync the Mainnet +* CPU with 8 cores +* 16GB RAM +* 2TB free storage space to sync the Mainnet Recommended: +* CPU with 16+ cores(32+ cores for a super representative) +* 32GB+ RAM(64GB+ for a super representative) +* High Performance SSD with at least 2.5TB free space +* 100+ MB/s download Internet service -- CPU with 16+ cores(32+ cores for a super representative) -- 32GB+ RAM(64GB+ for a super representative) -- High Performance SSD with at least 2.5TB free space -- 100+ MB/s download Internet service ## Running a full node for mainnet - -Full node has full historical data, it is the entry point into the TRON network , it can be used by other processes as a gateway into the TRON network via HTTP and GRPC endpoints. You can interact with the TRON network through full node:transfer assets, deploy contracts, interact with contracts and so on. `-c` parameter specifies a configuration file to run a full node: - -```bash -$ nohup java -Xms9G -Xmx9G -XX:ReservedCodeCacheSize=256m \ - -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m \ - -XX:MaxDirectMemorySize=1G -XX:+PrintGCDetails \ - -XX:+PrintGCDateStamps -Xloggc:gc.log \ - -XX:+UseConcMarkSweepGC -XX:NewRatio=2 \ - -XX:+CMSScavengeBeforeRemark -XX:+ParallelRefProcEnabled \ - -XX:+HeapDumpOnOutOfMemoryError \ - -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 \ - -jar FullNode.jar -c main_net_config.conf >> start.log 2>&1 & -``` - +Full node has full historical data, it is the entry point into the TRON network , it can be used by other processes as a gateway into the TRON network via HTTP and GRPC endpoints. You can interact with the TRON network through full node:transfer assets, deploy contracts, interact with contracts and so on. `-c ` parameter specifies a configuration file to run a full node: + ```bash + $ nohup java -Xms9G -Xmx9G -XX:ReservedCodeCacheSize=256m \ + -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m \ + -XX:MaxDirectMemorySize=1G -XX:+PrintGCDetails \ + -XX:+PrintGCDateStamps -Xloggc:gc.log \ + -XX:+UseConcMarkSweepGC -XX:NewRatio=2 \ + -XX:+CMSScavengeBeforeRemark -XX:+ParallelRefProcEnabled \ + -XX:+HeapDumpOnOutOfMemoryError \ + -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 \ + -jar FullNode.jar -c main_net_config.conf >> start.log 2>&1 & + ``` ## Running a super representative node for mainnet +Adding the `--witness` parameter to the startup command, full node will run as a super representative node. The super representative node supports all the functions of the full node and also supports block production. Before running, make sure you have a super representative account and get votes from others,once the number of obtained votes ranks in the top 27, your super representative node will participate in block production. -Adding the `--witness` parameter to the startup command, full node will run as a super representative node. The super representative node supports all the functions of the full node and also supports block production. Before running, make sure you have a super representative account and get votes from others. Once the number of obtained votes ranks in the top 27, your super representative node will participate in block production. - -Fill in the private key of super representative address into the `localwitness` list in the `main_net_config.conf`. Here is an example: - -``` - localwitness = [ - - ] -``` +Fill in the private key of super representative address into the `localwitness` list in the `main_net_config.conf`, here is an example: + ``` + localwitness = [ + 650950B193DDDDB35B6E48912DD28F7AB0E7140C1BFDEFD493348F02295BD812 + ] + ``` then run the following command to start the node: - -```bash -$ nohup java -Xms9G -Xmx9G -XX:ReservedCodeCacheSize=256m \ - -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m \ - -XX:MaxDirectMemorySize=1G -XX:+PrintGCDetails \ - -XX:+PrintGCDateStamps -Xloggc:gc.log \ - -XX:+UseConcMarkSweepGC -XX:NewRatio=2 \ - -XX:+CMSScavengeBeforeRemark -XX:+ParallelRefProcEnabled \ - -XX:+HeapDumpOnOutOfMemoryError \ - -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 \ - -jar FullNode.jar --witness -c main_net_config.conf >> start.log 2>&1 & -``` + ```bash + $ nohup java -Xms9G -Xmx9G -XX:ReservedCodeCacheSize=256m \ + -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m \ + -XX:MaxDirectMemorySize=1G -XX:+PrintGCDetails \ + -XX:+PrintGCDateStamps -Xloggc:gc.log \ + -XX:+UseConcMarkSweepGC -XX:NewRatio=2 \ + -XX:+CMSScavengeBeforeRemark -XX:+ParallelRefProcEnabled \ + -XX:+HeapDumpOnOutOfMemoryError \ + -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 \ + -jar FullNode.jar --witness -c main_net_config.conf >> start.log 2>&1 & + ``` ## Quick Start Tool - -An easier way to build and run java-tron is to use `start.sh`. `start.sh` is a quick start script written in the Shell language. You can use it to build and run java-tron quickly and easily. +An easier way to build and run java-tron is to use `start.sh`, `start.sh` is a quick start script written in shell language, you can use it to build and run java-tron quickly and easily. Here are some common use cases of the scripting tool - -- Use `start.sh` to start a full node with the downloaded `FullNode.jar` -- Use `start.sh` to download the latest `FullNode.jar` and start a full node. -- Use `start.sh` to download the latest source code and compile a `FullNode.jar` and then start a full node. +* Use `start.sh` to start a full node with the downloaded `FullNode.jar` +* Use `start.sh` to download the latest `FullNode.jar` and start a full node. +* Use `start.sh` to download the latest source code and compile a `FullNode.jar` and then start a full node. For more details, please refer to the tool [guide](./shell.md). ## Run inside Docker container One of the quickest ways to get `java-tron` up and running on your machine is by using Docker: - ```shell $ docker run -d --name="java-tron" \ -v /your_path/output-directory:/java-tron/output-directory \ @@ -170,7 +155,6 @@ $ docker run -d --name="java-tron" \ This will mount the `output-directory` and `logs` directories on the host, the docker.sh tool can also be used to simplify the use of docker, see more [here](docker/docker.md). # Community - [Tron Developers & SRs](https://discord.gg/hqKvyAM) is Tron's official Discord channel. Feel free to join this channel if you have any questions. [Core Devs Community](https://t.me/troncoredevscommunity) is the Telegram channel for java-tron community developers. If you want to contribute to java-tron, please join this channel. @@ -178,27 +162,22 @@ This will mount the `output-directory` and `logs` directories on the host, the d [tronprotocol/allcoredev](https://gitter.im/tronprotocol/allcoredev) is the official Gitter channel for developers. # Contribution - Thank you for considering to help out with the source code! If you'd like to contribute to java-tron, please see the [Contribution Guide](./CONTRIBUTING.md) for more details. -# Resources - -- [Medium](https://medium.com/@coredevs) java-tron's official technical articles are published there. -- [Documentation](https://tronprotocol.github.io/documentation-en/introduction/) java-tron's official technical documentation website. -- [Test network](http://nileex.io/) A stable test network of TRON contributed by TRON community. -- [Tronscan](https://tronscan.org/#/) TRON network blockchain browser. -- [Wallet-cli](https://github.com/tronprotocol/wallet-cli) TRON network wallet using command line. -- [TIP](https://github.com/tronprotocol/tips) TRON Improvement Proposal (TIP) describes standards for the TRON network. -- [TP](https://github.com/tronprotocol/tips/tree/master/tp) TRON Protocol (TP) describes standards already implemented in TRON network but not published as a TIP. +# Resources +* [Medium](https://medium.com/@coredevs) java-tron's official technical articles are published there. +* [Documentation](https://tronprotocol.github.io/documentation-en/introduction/) java-tron's official technical documentation website. +* [Test network](http://nileex.io/) A stable test network of TRON contributed by TRON community. +* [Tronscan](https://tronscan.org/#/) TRON network blockchain browser. +* [Wallet-cli](https://github.com/tronprotocol/wallet-cli) TRON network wallet using command line. +* [TIP](https://github.com/tronprotocol/tips) TRON Improvement Proposal (TIP) describes standards for the TRON network. +* [TP](https://github.com/tronprotocol/tips/tree/master/tp) TRON Protocol (TP) describes standards already implemented in TRON network but not published as a TIP. # Integrity Check - -- After January 3, 2023, the release files will be signed using a GPG key pair, and the correctness of the signature will be verified using the following public key: +* After January 3, 2023, releases are signed the gpg key: ``` pub: 1254 F859 D2B1 BD9F 66E7 107D F859 BCB4 4A28 290B uid: build@tron.network ``` - # License - java-tron is released under the [LGPLv3 license](https://github.com/tronprotocol/java-tron/blob/master/LICENSE). diff --git a/Tron protobuf protocol document.md b/Tron protobuf protocol document.md index 2ba2c3113a3..852ff313797 100644 --- a/Tron protobuf protocol document.md +++ b/Tron protobuf protocol document.md @@ -546,11 +546,11 @@ Transaction and transaction-related messages. message `raw` - `ref_block_bytes`: intercepted part of the now block bytes in transaction head. + `ref_block_bytes`: Deprecated. - `ref_block_num`: Deprecated. + `ref_block_num`: now block number in transaction head. - `ref_block_hash`:intercepted part of the now block hash in transaction head.. + `ref_block_hash`: now block hash in transaction head. `expiration`: the expiration time in transaction head. @@ -565,15 +565,15 @@ Transaction and transaction-related messages. ```java message raw { bytes ref_block_bytes = 1; - int64 ref_block_num = 3; + int64 ref_block_num = 3; bytes ref_block_hash = 4; - int64 expiration = 8; + int64 expiration = 8; repeated authority auths = 9; - bytes data = 10; + bytes data = 10; repeated Contract contract = 11; - bytes scripts = 12; + bytes scripts = 12; int64 timestamp = 14; - int64 fee_limit = 18; + int64 fee_limit = 18; } ``` diff --git a/actuator/build.gradle b/actuator/build.gradle index 9b200064fb0..a0ce72b0ee6 100644 --- a/actuator/build.gradle +++ b/actuator/build.gradle @@ -1,9 +1,25 @@ description = "actuator – a series of transactions for blockchain." +// Dependency versions +// --------------------------------------- + +def junitVersion = "4.13.2" +def mockitoVersion = "2.1.0" +def testNgVersion = "6.11" +def slf4jVersion = "1.7.25" +// -------------------------------------- + dependencies { compile project(":chainbase") compile project(":protocol") compile project(":crypto") + testImplementation "junit:junit:$junitVersion" + testImplementation "org.mockito:mockito-core:$mockitoVersion" + + compile "org.slf4j:jcl-over-slf4j:$slf4jVersion" + compile group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.69' + compile group: 'commons-codec', name: 'commons-codec', version: '1.11' + compile 'org.reflections:reflections:0.9.11' } test { diff --git a/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java b/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java index ae01f4834a9..35899284c3a 100644 --- a/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java +++ b/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java @@ -727,26 +727,6 @@ public static void validator(DynamicPropertiesStore dynamicPropertiesStore, } break; } - case ALLOW_OLD_REWARD_OPT: { - if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_7_4)) { - throw new ContractValidateException( - "Bad chain parameter id [ALLOW_OLD_REWARD_OPT]"); - } - if (dynamicPropertiesStore.allowOldRewardOpt()) { - throw new ContractValidateException( - "[ALLOW_OLD_REWARD_OPT] has been valid, no need to propose again"); - } - if (value != 1) { - throw new ContractValidateException( - "This value[ALLOW_OLD_REWARD_OPT] is only allowed to be 1"); - } - if (!dynamicPropertiesStore.useNewRewardAlgorithm()) { - throw new ContractValidateException( - "[ALLOW_NEW_REWARD] or [ALLOW_TVM_VOTE] proposal must be approved " - + "before [ALLOW_OLD_REWARD_OPT] can be proposed"); - } - break; - } default: break; } @@ -822,8 +802,7 @@ public enum ProposalType { // current value, value range DYNAMIC_ENERGY_MAX_FACTOR(75), // 0, [0, 100_000] ALLOW_TVM_SHANGHAI(76), // 0, 1 ALLOW_CANCEL_ALL_UNFREEZE_V2(77), // 0, 1 - MAX_DELEGATE_LOCK_PERIOD(78), // (86400, 10512000] - ALLOW_OLD_REWARD_OPT(79); // 0, 1 + MAX_DELEGATE_LOCK_PERIOD(78); // (86400, 10512000] private long code; diff --git a/build.gradle b/build.gradle index a56be97afa1..8aad8910153 100644 --- a/build.gradle +++ b/build.gradle @@ -38,7 +38,12 @@ subprojects { dependencies { compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25' compile group: 'org.slf4j', name: 'jcl-over-slf4j', version: '1.7.25' + compile "org.slf4j:jcl-over-slf4j:1.7.25" compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.9' + compileOnly 'org.projectlombok:lombok:1.18.12' + annotationProcessor 'org.projectlombok:lombok:1.18.12' + testCompileOnly 'org.projectlombok:lombok:1.18.12' + testAnnotationProcessor 'org.projectlombok:lombok:1.18.12' compile group: 'com.google.guava', name: 'guava', version: '30.1-jre' compile "com.google.code.findbugs:jsr305:3.0.0" compile group: 'org.springframework', name: 'spring-context', version: '5.3.18' @@ -47,15 +52,7 @@ subprojects { compile group: 'org.apache.commons', name: 'commons-math', version: '2.2' compile "org.apache.commons:commons-collections4:4.1" compile group: 'joda-time', name: 'joda-time', version: '2.3' - compile group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.69' - - compileOnly 'org.projectlombok:lombok:1.18.12' - annotationProcessor 'org.projectlombok:lombok:1.18.12' - testCompileOnly 'org.projectlombok:lombok:1.18.12' - testAnnotationProcessor 'org.projectlombok:lombok:1.18.12' - testImplementation group: 'junit', name: 'junit', version: '4.13.2' - testImplementation "org.mockito:mockito-core:2.13.0" } task sourcesJar(type: Jar, dependsOn: classes) { diff --git a/chainbase/build.gradle b/chainbase/build.gradle index 408fe56ba42..a2868aa78b4 100644 --- a/chainbase/build.gradle +++ b/chainbase/build.gradle @@ -2,16 +2,46 @@ description = "chainbase – a decentralized database for blockchain." // Dependency versions // --------------------------------------- + +def junitVersion = "4.13.2" +def mockitoVersion = "2.1.0" +def testNgVersion = "6.11" def jacocoVersion = "0.8.0" +def leveldbVersion = "1.8" def jansiVersion = "1.16" // -------------------------------------- +static def isWindows() { + return org.gradle.internal.os.OperatingSystem.current().isWindows() +} + +if (isWindows()) { + ext { + leveldbGroup = "org.ethereum" + leveldbName = "leveldbjni-all" + leveldbVersion = "1.18.3" + } +} else { + ext { + leveldbGroup = "org.fusesource.leveldbjni" + leveldbName = "leveldbjni-all" + leveldbVersion = "1.8" + } +} + dependencies { + testImplementation "junit:junit:$junitVersion" + testImplementation "org.mockito:mockito-core:$mockitoVersion" + + compile group: leveldbGroup, name: leveldbName, version: leveldbVersion + compile "org.fusesource.jansi:jansi:$jansiVersion" + compile group: 'org.rocksdb', name: 'rocksdbjni', version: '5.15.10' + compile group: 'com.typesafe', name: 'config', version: '1.3.2' + compile 'io.github.tronprotocol:zksnark-java-sdk:1.0.0' + compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.8.5' compile project(":protocol") compile project(":common") compile project(":crypto") - compile "org.fusesource.jansi:jansi:$jansiVersion" - compile 'io.github.tronprotocol:zksnark-java-sdk:1.0.0' compile 'org.reflections:reflections:0.9.11' } diff --git a/chainbase/src/main/java/org/tron/common/utils/ForkController.java b/chainbase/src/main/java/org/tron/common/utils/ForkController.java index 7cbac28e781..c3db883a011 100644 --- a/chainbase/src/main/java/org/tron/common/utils/ForkController.java +++ b/chainbase/src/main/java/org/tron/common/utils/ForkController.java @@ -78,7 +78,7 @@ private boolean passOld(int version) { private boolean passNew(int version) { ForkBlockVersionEnum versionEnum = ForkBlockVersionEnum.getForkBlockVersionEnum(version); if (versionEnum == null) { - logger.warn("Not exist block version: {}.", version); + logger.error("Not exist block version: {}.", version); return false; } long latestBlockTime = manager.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp(); diff --git a/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java index a588b28c748..9598fd99a6b 100755 --- a/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java @@ -102,6 +102,7 @@ public class TransactionCapsule implements ProtoCapsule { @Setter private TransactionTrace trxTrace; + private StringBuilder toStringBuff = new StringBuilder(); @Getter @Setter private long time; @@ -737,7 +738,8 @@ public Transaction getInstance() { @Override public String toString() { - StringBuilder toStringBuff = new StringBuilder(); + + toStringBuff.setLength(0); toStringBuff.append("TransactionCapsule \n[ "); toStringBuff.append("hash=").append(getTransactionId()).append("\n"); diff --git a/chainbase/src/main/java/org/tron/core/capsule/utils/MerkleTree.java b/chainbase/src/main/java/org/tron/core/capsule/utils/MerkleTree.java index 94d22f4b474..47ac45c9fb8 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/utils/MerkleTree.java +++ b/chainbase/src/main/java/org/tron/core/capsule/utils/MerkleTree.java @@ -5,12 +5,10 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; import lombok.Getter; -import net.jcip.annotations.NotThreadSafe; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.Sha256Hash; @Getter -@NotThreadSafe public class MerkleTree { private static volatile MerkleTree instance; diff --git a/chainbase/src/main/java/org/tron/core/db/common/iterator/DBIterator.java b/chainbase/src/main/java/org/tron/core/db/common/iterator/DBIterator.java index afbacac35db..f706623693f 100755 --- a/chainbase/src/main/java/org/tron/core/db/common/iterator/DBIterator.java +++ b/chainbase/src/main/java/org/tron/core/db/common/iterator/DBIterator.java @@ -1,71 +1,9 @@ package org.tron.core.db.common.iterator; -import com.google.common.collect.Iterators; -import com.google.common.collect.UnmodifiableIterator; -import com.google.common.primitives.Bytes; import java.io.Closeable; import java.util.Iterator; import java.util.Map.Entry; -import java.util.NoSuchElementException; -public interface DBIterator extends Iterator>, AutoCloseable, Closeable { +public interface DBIterator extends Iterator>, Closeable { - void seek(byte[] key); - - void seekToFirst(); - - void seekToLast(); - - /** - * An iterator is either positioned at a key/value pair, or - * not valid. This method returns true iff the iterator is valid. - * - * REQUIRES: iterator not closed - * - * @throws IllegalStateException if the iterator is closed. - * @return an iterator is either positioned at a key/value pair - */ - boolean valid(); - - /** - * The underlying storage for - * the returned slice is valid only until the next modification of - * the iterator. - * - * REQUIRES: valid() && !closed - * - * @throws IllegalStateException if the iterator is closed. - * @throws NoSuchElementException if the iterator is not valid. - * - * @return the key for the current entry - */ - byte[] getKey(); - - /** - * The underlying storage for - * the returned slice is valid only until the next modification of - * the iterator. - * - * REQUIRES: valid() && !closed - * - * @throws IllegalStateException if the iterator is closed. - * @throws NoSuchElementException if the iterator is not valid. - * - * @return the value for the current entry - */ - byte[] getValue(); - - /** - * @throws IllegalStateException if the iterator is closed. - */ - void checkState(); - - /** - * @throws NoSuchElementException if the iterator is not valid. - */ - default void checkValid() { - if (!valid()) { - throw new NoSuchElementException(); - } - } } diff --git a/chainbase/src/main/java/org/tron/core/db/common/iterator/RockStoreIterator.java b/chainbase/src/main/java/org/tron/core/db/common/iterator/RockStoreIterator.java index 541f71348af..a8c4cff2066 100644 --- a/chainbase/src/main/java/org/tron/core/db/common/iterator/RockStoreIterator.java +++ b/chainbase/src/main/java/org/tron/core/db/common/iterator/RockStoreIterator.java @@ -3,7 +3,6 @@ import java.io.IOException; import java.util.Map.Entry; import java.util.NoSuchElementException; -import java.util.concurrent.atomic.AtomicBoolean; import lombok.extern.slf4j.Slf4j; import org.rocksdb.RocksIterator; @@ -14,7 +13,7 @@ public final class RockStoreIterator implements DBIterator { private final RocksIterator dbIterator; private boolean first = true; - private final AtomicBoolean close = new AtomicBoolean(false); + private boolean valid = true; public RockStoreIterator(RocksIterator dbIterator) { this.dbIterator = dbIterator; @@ -22,14 +21,12 @@ public RockStoreIterator(RocksIterator dbIterator) { @Override public void close() throws IOException { - if (close.compareAndSet(false, true)) { - dbIterator.close(); - } + dbIterator.close(); } @Override public boolean hasNext() { - if (close.get()) { + if (!valid) { return false; } boolean hasNext = false; @@ -40,12 +37,13 @@ public boolean hasNext() { first = false; } if (!(hasNext = dbIterator.isValid())) { // false is last item - close(); + dbIterator.close(); + valid = false; } } catch (Exception e) { logger.error(e.getMessage(), e); try { - close(); + dbIterator.close(); } catch (Exception e1) { logger.error(e.getMessage(), e); } @@ -55,7 +53,7 @@ public boolean hasNext() { @Override public Entry next() { - if (close.get()) { + if (!valid) { throw new NoSuchElementException(); } byte[] key = dbIterator.key(); @@ -78,50 +76,4 @@ public byte[] setValue(byte[] value) { } }; } - - @Override - public void seek(byte[] key) { - checkState(); - dbIterator.seek(key); - this.first = false; - } - - @Override - public void seekToFirst() { - checkState(); - dbIterator.seekToFirst(); - this.first = false; - } - - @Override - public void seekToLast() { - checkState(); - dbIterator.seekToLast(); - this.first = false; - } - - @Override - public boolean valid() { - checkState(); - return dbIterator.isValid(); - } - - @Override - public byte[] getKey() { - checkValid(); - return dbIterator.key(); - } - - @Override - public byte[] getValue() { - checkValid(); - return dbIterator.value(); - } - - @Override - public void checkState() { - if (close.get()) { - throw new IllegalStateException("iterator has been closed"); - } - } -} +} \ No newline at end of file diff --git a/chainbase/src/main/java/org/tron/core/db/common/iterator/StoreIterator.java b/chainbase/src/main/java/org/tron/core/db/common/iterator/StoreIterator.java index d771716a7e8..292bb421e54 100755 --- a/chainbase/src/main/java/org/tron/core/db/common/iterator/StoreIterator.java +++ b/chainbase/src/main/java/org/tron/core/db/common/iterator/StoreIterator.java @@ -3,7 +3,6 @@ import java.io.IOException; import java.util.Map.Entry; import java.util.NoSuchElementException; -import java.util.concurrent.atomic.AtomicBoolean; import lombok.extern.slf4j.Slf4j; import org.iq80.leveldb.DBIterator; @@ -14,7 +13,7 @@ public final class StoreIterator implements org.tron.core.db.common.iterator.DBI private final DBIterator dbIterator; private boolean first = true; - private final AtomicBoolean close = new AtomicBoolean(false); + private boolean valid = true; public StoreIterator(DBIterator dbIterator) { this.dbIterator = dbIterator; @@ -22,14 +21,12 @@ public StoreIterator(DBIterator dbIterator) { @Override public void close() throws IOException { - if (close.compareAndSet(false, true)) { - dbIterator.close(); - } + dbIterator.close(); } @Override public boolean hasNext() { - if (close.get()) { + if (!valid) { return false; } @@ -42,7 +39,8 @@ public boolean hasNext() { } if (!(hasNext = dbIterator.hasNext())) { // false is last item - close(); + dbIterator.close(); + valid = false; } } catch (Exception e) { logger.error(e.getMessage(), e); @@ -53,7 +51,7 @@ public boolean hasNext() { @Override public Entry next() { - if (close.get()) { + if (!valid) { throw new NoSuchElementException(); } return dbIterator.next(); @@ -63,51 +61,4 @@ public Entry next() { public void remove() { throw new UnsupportedOperationException(); } - - @Override - public void seek(byte[] key) { - checkState(); - dbIterator.seek(key); - this.first = false; - } - - @Override - public void seekToFirst() { - checkState(); - dbIterator.seekToFirst(); - this.first = false; - } - - @Override - public void seekToLast() { - checkState(); - dbIterator.seekToLast(); - this.first = false; - } - - @Override - public boolean valid() { - checkState(); - return dbIterator.hasNext(); - } - - @Override - public byte[] getKey() { - checkValid(); - return dbIterator.peekNext().getKey(); - } - - @Override - public byte[] getValue() { - checkValid(); - return dbIterator.peekNext().getValue(); - } - - @Override - public void checkState() { - if (close.get()) { - throw new IllegalStateException("iterator has been closed"); - } - } } - diff --git a/chainbase/src/main/java/org/tron/core/service/MortgageService.java b/chainbase/src/main/java/org/tron/core/service/MortgageService.java index 805245d53f2..e9b00a38201 100644 --- a/chainbase/src/main/java/org/tron/core/service/MortgageService.java +++ b/chainbase/src/main/java/org/tron/core/service/MortgageService.java @@ -4,15 +4,12 @@ import java.math.BigInteger; import java.util.Comparator; import java.util.List; -import java.util.stream.Collectors; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.bouncycastle.util.encoders.Hex; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import org.tron.common.utils.Pair; import org.tron.common.utils.StringUtil; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.WitnessCapsule; @@ -21,6 +18,7 @@ import org.tron.core.store.DelegationStore; import org.tron.core.store.DynamicPropertiesStore; import org.tron.core.store.WitnessStore; +import org.tron.protos.Protocol.Vote; @Slf4j(topic = "mortgage") @Component @@ -39,9 +37,6 @@ public class MortgageService { @Setter private AccountStore accountStore; - @Autowired - private RewardViCalService rewardViCalService; - public void initStore(WitnessStore witnessStore, DelegationStore delegationStore, DynamicPropertiesStore dynamicPropertiesStore, AccountStore accountStore) { this.witnessStore = witnessStore; @@ -167,21 +162,21 @@ public long queryReward(byte[] address) { return reward + accountCapsule.getAllowance(); } - private long computeReward(long cycle, List> votes) { + private long computeReward(long cycle, AccountCapsule accountCapsule) { long reward = 0; - for (Pair vote : votes) { - byte[] srAddress = vote.getKey(); + for (Vote vote : accountCapsule.getVotesList()) { + byte[] srAddress = vote.getVoteAddress().toByteArray(); long totalReward = delegationStore.getReward(cycle, srAddress); - if (totalReward <= 0) { - continue; - } long totalVote = delegationStore.getWitnessVote(cycle, srAddress); if (totalVote == DelegationStore.REMARK || totalVote == 0) { continue; } - long userVote = vote.getValue(); + long userVote = vote.getVoteCount(); double voteRate = (double) userVote / totalVote; reward += voteRate * totalReward; + logger.debug("ComputeReward {}, {}, {}, {}, {}, {}, {}.", cycle, + Hex.toHexString(accountCapsule.getAddress().toByteArray()), Hex.toHexString(srAddress), + userVote, totalVote, totalReward, reward); } return reward; } @@ -202,24 +197,23 @@ private long computeReward(long beginCycle, long endCycle, AccountCapsule accoun long reward = 0; long newAlgorithmCycle = dynamicPropertiesStore.getNewRewardAlgorithmEffectiveCycle(); - List> srAddresses = accountCapsule.getVotesList().stream() - .map(vote -> new Pair<>(vote.getVoteAddress().toByteArray(), vote.getVoteCount())) - .collect(Collectors.toList()); if (beginCycle < newAlgorithmCycle) { long oldEndCycle = Math.min(endCycle, newAlgorithmCycle); - reward = getOldReward(beginCycle, oldEndCycle, srAddresses); + for (long cycle = beginCycle; cycle < oldEndCycle; cycle++) { + reward += computeReward(cycle, accountCapsule); + } beginCycle = oldEndCycle; } if (beginCycle < endCycle) { - for (Pair vote : srAddresses) { - byte[] srAddress = vote.getKey(); + for (Vote vote : accountCapsule.getVotesList()) { + byte[] srAddress = vote.getVoteAddress().toByteArray(); BigInteger beginVi = delegationStore.getWitnessVi(beginCycle - 1, srAddress); BigInteger endVi = delegationStore.getWitnessVi(endCycle - 1, srAddress); BigInteger deltaVi = endVi.subtract(beginVi); if (deltaVi.signum() <= 0) { continue; } - long userVote = vote.getValue(); + long userVote = vote.getVoteCount(); reward += deltaVi.multiply(BigInteger.valueOf(userVote)) .divide(DelegationStore.DECIMAL_OF_VI_REWARD).longValue(); } @@ -263,15 +257,4 @@ private void sortWitness(List list) { list.sort(Comparator.comparingLong((ByteString b) -> getWitnessByAddress(b).getVoteCount()) .reversed().thenComparing(Comparator.comparingInt(ByteString::hashCode).reversed())); } - - private long getOldReward(long begin, long end, List> votes) { - if (dynamicPropertiesStore.allowOldRewardOpt()) { - return rewardViCalService.getNewRewardAlgorithmReward(begin, end, votes); - } - long reward = 0; - for (long cycle = begin; cycle < end; cycle++) { - reward += computeReward(cycle, votes); - } - return reward; - } } diff --git a/chainbase/src/main/java/org/tron/core/service/RewardViCalService.java b/chainbase/src/main/java/org/tron/core/service/RewardViCalService.java deleted file mode 100644 index e27990f0403..00000000000 --- a/chainbase/src/main/java/org/tron/core/service/RewardViCalService.java +++ /dev/null @@ -1,286 +0,0 @@ -package org.tron.core.service; - -import static org.tron.core.store.DelegationStore.DECIMAL_OF_VI_REWARD; -import static org.tron.core.store.DelegationStore.REMARK; - -import com.google.common.collect.Streams; -import com.google.common.primitives.Bytes; -import com.google.protobuf.ByteString; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import java.util.stream.LongStream; -import javax.annotation.PreDestroy; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.tron.common.error.TronDBException; -import org.tron.common.es.ExecutorServiceManager; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.MerkleRoot; -import org.tron.common.utils.Pair; -import org.tron.common.utils.Sha256Hash; -import org.tron.core.db.common.iterator.DBIterator; -import org.tron.core.db2.common.DB; -import org.tron.core.store.DelegationStore; -import org.tron.core.store.DynamicPropertiesStore; -import org.tron.core.store.RewardViStore; -import org.tron.core.store.WitnessStore; - -@Component -@Slf4j(topic = "rewardViCalService") -public class RewardViCalService { - - private final DB propertiesStore; - private final DB delegationStore; - private final DB witnessStore; - - @Autowired - private RewardViStore rewardViStore; - - private static final byte[] IS_DONE_KEY = new byte[]{0x00}; - private static final byte[] IS_DONE_VALUE = new byte[]{0x01}; - - private long newRewardCalStartCycle = Long.MAX_VALUE; - - private volatile long lastBlockNumber = -1; - - private static final String MAIN_NET_ROOT_HEX = - "9debcb9924055500aaae98cdee10501c5c39d4daa75800a996f4bdda73dbccd8"; - - private final Sha256Hash rewardViRoot = CommonParameter.getInstance().getStorage().getDbRoot( - "reward-vi", Sha256Hash.wrap(ByteString.fromHex(MAIN_NET_ROOT_HEX))); - - private final CountDownLatch lock = new CountDownLatch(1); - - private final ScheduledExecutorService es = ExecutorServiceManager - .newSingleThreadScheduledExecutor("rewardViCalService"); - - - @Autowired - public RewardViCalService(@Autowired DynamicPropertiesStore propertiesStore, - @Autowired DelegationStore delegationStore, @Autowired WitnessStore witnessStore) { - this.propertiesStore = propertiesStore.getDb(); - this.delegationStore = delegationStore.getDb(); - this.witnessStore = witnessStore.getDb(); - } - - public void init() { - // after init, we can get the latest block header number from db - this.newRewardCalStartCycle = this.getNewRewardAlgorithmEffectiveCycle(); - boolean ret = this.newRewardCalStartCycle != Long.MAX_VALUE; - if (ret) { - // checkpoint is flushed to db, we can start rewardViCalService immediately - lastBlockNumber = Long.MAX_VALUE; - } - es.scheduleWithFixedDelay(this::maybeRun, 0, 3, TimeUnit.SECONDS); - } - - private boolean enableNewRewardAlgorithm() { - this.newRewardCalStartCycle = this.getNewRewardAlgorithmEffectiveCycle(); - boolean ret = this.newRewardCalStartCycle != Long.MAX_VALUE; - if (ret && lastBlockNumber == -1) { - lastBlockNumber = this.getLatestBlockHeaderNumber(); - } - return ret; - } - - private boolean isDone() { - return rewardViStore.has(IS_DONE_KEY); - } - - private void maybeRun() { - try { - if (enableNewRewardAlgorithm()) { - if (this.newRewardCalStartCycle > 1) { - if (isDone()) { - this.clearUp(true); - logger.info("rewardViCalService is already done"); - } else { - if (lastBlockNumber == Long.MAX_VALUE // start rewardViCalService immediately - || this.getLatestBlockHeaderNumber() > lastBlockNumber) { - // checkpoint is flushed to db, so we can start rewardViCalService - startRewardCal(); - clearUp(true); - } else { - logger.info("startRewardCal will run after checkpoint is flushed to db"); - } - } - } else { - clearUp(false); - logger.info("rewardViCalService is no need to run"); - } - } - } catch (Exception e) { - logger.error(" Find fatal error, program will be exited soon.", e); - System.exit(1); - } - } - - private void clearUp(boolean isDone) { - lock.countDown(); - if (isDone) { - calcMerkleRoot(); - } - es.shutdown(); - } - - @PreDestroy - private void destroy() { - es.shutdownNow(); - } - - - public long getNewRewardAlgorithmReward(long beginCycle, long endCycle, - List> votes) { - if (!isDone()) { - logger.warn("rewardViCalService is not done, wait for it"); - try { - lock.await(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new TronDBException(e); - } - } - - long reward = 0; - if (beginCycle < endCycle) { - for (Pair vote : votes) { - byte[] srAddress = vote.getKey(); - BigInteger beginVi = getWitnessVi(beginCycle - 1, srAddress); - BigInteger endVi = getWitnessVi(endCycle - 1, srAddress); - BigInteger deltaVi = endVi.subtract(beginVi); - if (deltaVi.signum() <= 0) { - continue; - } - long userVote = vote.getValue(); - reward += deltaVi.multiply(BigInteger.valueOf(userVote)) - .divide(DelegationStore.DECIMAL_OF_VI_REWARD).longValue(); - } - } - return reward; - - } - - private void calcMerkleRoot() { - logger.info("calcMerkleRoot start"); - DBIterator iterator = rewardViStore.iterator(); - iterator.seekToFirst(); - ArrayList ids = Streams.stream(iterator) - .map(this::getHash) - .collect(Collectors.toCollection(ArrayList::new)); - - Sha256Hash rewardViRootLocal = MerkleRoot.root(ids); - if (!Objects.equals(rewardViRoot, rewardViRootLocal)) { - logger.warn("Merkle root mismatch, expect: {}, actual: {}." - + " If you are quite sure that there is no miscalculation (not on the main network)" - + ", please configure 'storage.merkleRoot.reward-vi = {}'" - + "(for a specific network such as Nile, etc.) in config.conf to fix the hints", - rewardViRoot, rewardViRootLocal, rewardViRootLocal); - } - logger.info("calcMerkleRoot: {}", rewardViRootLocal); - } - - private Sha256Hash getHash(Map.Entry entry) { - return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - Bytes.concat(entry.getKey(), entry.getValue())); - } - - private void startRewardCal() { - logger.info("rewardViCalService start"); - rewardViStore.reset(); - DBIterator iterator = (DBIterator) witnessStore.iterator(); - iterator.seekToFirst(); - iterator.forEachRemaining(e -> accumulateWitnessReward(e.getKey())); - rewardViStore.put(IS_DONE_KEY, IS_DONE_VALUE); - logger.info("rewardViCalService is done"); - - } - - private void accumulateWitnessReward(byte[] witness) { - long startCycle = 1; - LongStream.range(startCycle, newRewardCalStartCycle) - .forEach(cycle -> accumulateWitnessVi(cycle, witness)); - } - - private void accumulateWitnessVi(long cycle, byte[] address) { - BigInteger preVi = getWitnessVi(cycle - 1, address); - long voteCount = getWitnessVote(cycle, address); - long reward = getReward(cycle, address); - if (reward == 0 || voteCount == 0) { // Just forward pre vi - if (!BigInteger.ZERO.equals(preVi)) { // Zero vi will not be record - setWitnessVi(cycle, address, preVi); - } - } else { // Accumulate delta vi - BigInteger deltaVi = BigInteger.valueOf(reward) - .multiply(DECIMAL_OF_VI_REWARD) - .divide(BigInteger.valueOf(voteCount)); - setWitnessVi(cycle, address, preVi.add(deltaVi)); - } - } - - private void setWitnessVi(long cycle, byte[] address, BigInteger value) { - byte[] k = buildViKey(cycle, address); - byte[] v = value.toByteArray(); - rewardViStore.put(k, v); - } - - private BigInteger getWitnessVi(long cycle, byte[] address) { - - byte[] v = rewardViStore.get(buildViKey(cycle, address)); - if (v == null) { - return BigInteger.ZERO; - } else { - return new BigInteger(v); - } - } - - private byte[] buildViKey(long cycle, byte[] address) { - return generateKey(cycle, address, "vi"); - } - - private long getReward(long cycle, byte[] address) { - byte[] value = this.delegationStore.get(generateKey(cycle, address, "reward")); - return value == null ? 0 : ByteArray.toLong(value); - } - - private long getWitnessVote(long cycle, byte[] address) { - byte[] value = this.delegationStore.get(generateKey(cycle, address, "vote")); - return value == null ? REMARK : ByteArray.toLong(value); - } - - private byte[] generateKey(long cycle, byte[] address, String suffix) { - return generateKey(cycle + "", address, suffix); - } - - private byte[] generateKey(String prefix, byte[] address, String suffix) { - StringBuilder sb = new StringBuilder(); - if (prefix != null) { - sb.append(prefix).append("-"); - } - sb.append(Hex.toHexString(address)); - if (suffix != null) { - sb.append("-").append(suffix); - } - return sb.toString().getBytes(); - } - - private long getNewRewardAlgorithmEffectiveCycle() { - byte[] value = this.propertiesStore.get("NEW_REWARD_ALGORITHM_EFFECTIVE_CYCLE".getBytes()); - return value == null ? Long.MAX_VALUE : ByteArray.toLong(value); - } - - private long getLatestBlockHeaderNumber() { - byte[] value = this.propertiesStore.get("latest_block_header_number".getBytes()); - return value == null ? 1 : ByteArray.toLong(value); - } -} - diff --git a/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java b/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java index bf788232640..f3059d31558 100644 --- a/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java +++ b/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java @@ -217,8 +217,6 @@ public class DynamicPropertiesStore extends TronStoreWithRevoking private static final byte[] MAX_DELEGATE_LOCK_PERIOD = "MAX_DELEGATE_LOCK_PERIOD".getBytes(); - private static final byte[] ALLOW_OLD_REWARD_OPT = "ALLOW_OLD_REWARD_OPT".getBytes(); - @Autowired private DynamicPropertiesStore(@Value("properties") String dbName) { super(dbName); @@ -2835,21 +2833,6 @@ public boolean supportMaxDelegateLockPeriod() { getUnfreezeDelayDays() > 0; } - public void saveAllowOldRewardOpt(long allowOldRewardOpt) { - this.put(ALLOW_OLD_REWARD_OPT, new BytesCapsule(ByteArray.fromLong(allowOldRewardOpt))); - } - - public boolean allowOldRewardOpt() { - return getAllowOldRewardOpt() == 1L; - } - - public long getAllowOldRewardOpt() { - return Optional.ofNullable(getUnchecked(ALLOW_OLD_REWARD_OPT)) - .map(BytesCapsule::getData) - .map(ByteArray::toLong) - .orElse(CommonParameter.getInstance().getAllowOldRewardOpt()); - } - private static class DynamicResourceProperties { private static final byte[] ONE_DAY_NET_LIMIT = "ONE_DAY_NET_LIMIT".getBytes(); diff --git a/chainbase/src/main/java/org/tron/core/store/RewardViStore.java b/chainbase/src/main/java/org/tron/core/store/RewardViStore.java deleted file mode 100755 index f173cecc00f..00000000000 --- a/chainbase/src/main/java/org/tron/core/store/RewardViStore.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.tron.core.store; - -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; -import org.tron.core.db.TronDatabase; -import org.tron.core.db.common.iterator.DBIterator; - -@Slf4j(topic = "DB") -@Component -public class RewardViStore extends TronDatabase { - - @Autowired - private RewardViStore(@Value("reward-vi") String dbName) { - super(dbName); - } - - @Override - public byte[] get(byte[] key) { - return dbSource.getData(key); - } - - @Override - public void put(byte[] key, byte[] item) { - dbSource.putData(key, item); - } - - @Override - public void delete(byte[] key) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean has(byte[] key) { - return dbSource.getData(key) != null; - } - - @Override - public DBIterator iterator() { - return ((DBIterator) dbSource.iterator()); - } -} diff --git a/common/build.gradle b/common/build.gradle index 6c1545e5d13..0431316c009 100644 --- a/common/build.gradle +++ b/common/build.gradle @@ -8,6 +8,7 @@ sourceCompatibility = 1.8 // Dependency versions // --------------------------------------- + def leveldbVersion = "1.8" // -------------------------------------- @@ -29,7 +30,13 @@ if (isWindows()) { } } +repositories { + mavenCentral() +} + dependencies { + testCompile group: 'junit', name: 'junit', version: '4.13.2' + compile group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.69' compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.13.4.1' compile "com.cedarsoftware:java-util:1.8.0" compile group: 'org.apache.httpcomponents', name: 'httpasyncclient', version: '4.1.1' @@ -46,7 +53,7 @@ dependencies { compile 'org.aspectj:aspectjrt:1.8.13' compile 'org.aspectj:aspectjweaver:1.8.13' compile 'org.aspectj:aspectjtools:1.8.13' - compile group: 'io.github.tronprotocol', name: 'libp2p', version: '2.2.1',{ + compile group: 'io.github.tronprotocol', name: 'libp2p', version: '2.1.0',{ exclude group: 'io.grpc', module: 'grpc-context' exclude group: 'io.grpc', module: 'grpc-core' exclude group: 'io.grpc', module: 'grpc-netty' diff --git a/common/src/main/java/org/tron/common/parameter/CommonParameter.java b/common/src/main/java/org/tron/common/parameter/CommonParameter.java index 95a1eb2d0ae..f8f6e6c5edb 100644 --- a/common/src/main/java/org/tron/common/parameter/CommonParameter.java +++ b/common/src/main/java/org/tron/common/parameter/CommonParameter.java @@ -176,7 +176,7 @@ public class CommonParameter { public int nodeListenPort; @Getter @Setter - public String nodeLanIp; + public String nodeDiscoveryBindIp; @Getter @Setter public String nodeExternalIp; @@ -255,9 +255,6 @@ public class CommonParameter { public int maxHeaderListSize; @Getter @Setter - public boolean isRpcReflectionServiceEnable; - @Getter - @Setter @Parameter(names = {"--validate-sign-thread"}, description = "Num of validate thread") public int validateSignThreadNum; @Getter @@ -654,18 +651,6 @@ public class CommonParameter { @Setter public long allowCancelAllUnfreezeV2; - @Getter - @Setter - public boolean unsolidifiedBlockCheck; - - @Getter - @Setter - public int maxUnsolidifiedBlocks; - - @Getter - @Setter - public long allowOldRewardOpt; - private static double calcMaxTimeRatio() { //return max(2.0, min(5.0, 5 * 4.0 / max(Runtime.getRuntime().availableProcessors(), 1))); return 5.0; diff --git a/common/src/main/java/org/tron/common/utils/MerkleRoot.java b/common/src/main/java/org/tron/common/utils/MerkleRoot.java deleted file mode 100644 index ccd8905b6c5..00000000000 --- a/common/src/main/java/org/tron/common/utils/MerkleRoot.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.tron.common.utils; - -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.IntStream; -import lombok.Getter; - -public class MerkleRoot { - - private MerkleRoot() { - - } - - public static Sha256Hash root(List hashList) { - List leaves = createLeaves(hashList); - while (leaves.size() > 1) { - leaves = createParentLeaves(leaves); - } - return leaves.isEmpty() ? Sha256Hash.ZERO_HASH : leaves.get(0).hash; - } - - private static List createParentLeaves(List leaves) { - int step = 2; - int len = leaves.size(); - return IntStream.iterate(0, i -> i + step) - .limit(len) - .filter(i -> i < len) - .mapToObj(i -> { - Leaf right = i + 1 < len ? leaves.get(i + 1) : null; - return createLeaf(leaves.get(i), right); - }).collect(Collectors.toList()); - } - - private static List createLeaves(List hashList) { - int step = 2; - int len = hashList.size(); - return IntStream.iterate(0, i -> i + step) - .limit(len) - .filter(i -> i < len) - .mapToObj(i -> { - Leaf right = i + 1 < len ? createLeaf(hashList.get(i + 1)) : null; - return createLeaf(createLeaf(hashList.get(i)), right); - }).collect(Collectors.toList()); - } - - private static Leaf createLeaf(Leaf left, Leaf right) { - Leaf leaf = new Leaf(); - leaf.hash = right == null ? left.hash : computeHash(left.hash, right.hash); - return leaf; - } - - private static Leaf createLeaf(Sha256Hash hash) { - Leaf leaf = new Leaf(); - leaf.hash = hash; - return leaf; - } - - private static Sha256Hash computeHash(Sha256Hash leftHash, Sha256Hash rightHash) { - return Sha256Hash.of(true, - leftHash.getByteString().concat(rightHash.getByteString()).toByteArray()); - } - - @Getter - private static class Leaf { - - private Sha256Hash hash; - } -} diff --git a/common/src/main/java/org/tron/core/Constant.java b/common/src/main/java/org/tron/core/Constant.java index 2cd9ea95f15..ba867793b41 100644 --- a/common/src/main/java/org/tron/core/Constant.java +++ b/common/src/main/java/org/tron/core/Constant.java @@ -151,8 +151,6 @@ public class Constant { public static final String NODE_RPC_MAX_HEADER_LIST_SIZE = "node.rpc.maxHeaderListSize"; - public static final String NODE_RPC_REFLECTION_SERVICE = "node.rpc.reflectionService"; - public static final String NODE_OPEN_HISTORY_QUERY_WHEN_LITEFN = "node.openHistoryQueryWhenLiteFN"; public static final String BLOCK_MAINTENANCE_TIME_INTERVAL = "block.maintenanceTimeInterval"; @@ -281,6 +279,8 @@ public class Constant { public static final String EVENT_SUBSCRIBE_CONTRACT_ADDRESS = "event.subscribe.filter.contractAddress"; public static final String EVENT_SUBSCRIBE_CONTRACT_TOPIC = "event.subscribe.filter.contractTopic"; + public static final String NODE_DISCOVERY_BIND_IP = "node.discovery.bind.ip"; + public static final String NODE_DISCOVERY_EXTERNAL_IP = "node.discovery.external.ip"; public static final String NODE_BACKUP_PRIORITY = "node.backup.priority"; @@ -371,9 +371,4 @@ public class Constant { public static final String DYNAMIC_CONFIG_CHECK_INTERVAL = "node.dynamicConfig.checkInterval"; public static final String COMMITTEE_ALLOW_TVM_SHANGHAI = "committee.allowTvmShangHai"; - - public static final String UNSOLIDIFIED_BLOCK_CHECK = "node.unsolidifiedBlockCheck"; - - public static final String MAX_UNSOLIDIFIED_BLOCKS = "node.maxUnsolidifiedBlocks"; - public static final String COMMITTEE_ALLOW_OLD_REWARD_OPT = "committee.allowOldRewardOpt"; } diff --git a/common/src/main/java/org/tron/core/config/Parameter.java b/common/src/main/java/org/tron/core/config/Parameter.java index 247826af77a..b1a948e9fdf 100644 --- a/common/src/main/java/org/tron/core/config/Parameter.java +++ b/common/src/main/java/org/tron/core/config/Parameter.java @@ -22,8 +22,7 @@ public enum ForkBlockVersionEnum { VERSION_4_6(25, 1596780000000L, 80), VERSION_4_7(26, 1596780000000L, 80), VERSION_4_7_1(27, 1596780000000L, 80), - VERSION_4_7_2(28, 1596780000000L, 80), - VERSION_4_7_4(29, 1596780000000L, 80); + VERSION_4_7_2(28, 1596780000000L, 80); // if add a version, modify BLOCK_VERSION simultaneously @Getter @@ -72,7 +71,7 @@ public class ChainConstant { public static final int SINGLE_REPEAT = 1; public static final int BLOCK_FILLED_SLOTS_NUMBER = 128; public static final int MAX_FROZEN_NUMBER = 1; - public static final int BLOCK_VERSION = 29; + public static final int BLOCK_VERSION = 28; public static final long FROZEN_PERIOD = 86_400_000L; public static final long DELEGATE_PERIOD = 3 * 86_400_000L; public static final long TRX_PRECISION = 1000_000L; diff --git a/common/src/main/java/org/tron/core/config/args/Storage.java b/common/src/main/java/org/tron/core/config/args/Storage.java index 9cf6eb6bab1..22dc239c167 100644 --- a/common/src/main/java/org/tron/core/config/args/Storage.java +++ b/common/src/main/java/org/tron/core/config/args/Storage.java @@ -16,7 +16,6 @@ package org.tron.core.config.args; import com.google.common.collect.Maps; -import com.google.protobuf.ByteString; import com.typesafe.config.Config; import com.typesafe.config.ConfigObject; import java.io.File; @@ -33,7 +32,6 @@ import org.tron.common.utils.DbOptionalsUtils; import org.tron.common.utils.FileUtil; import org.tron.common.utils.Property; -import org.tron.common.utils.Sha256Hash; /** * Custom storage configurations @@ -81,8 +79,6 @@ public class Storage { private static final String CACHE_STRATEGIES = "storage.cache.strategies"; public static final String TX_CACHE_INIT_OPTIMIZATION = "storage.txCache.initOptimization"; - private static final String MERKLE_ROOT = "storage.merkleRoot"; - /** * Default values of directory */ @@ -167,9 +163,6 @@ public class Storage { @Getter private Map propertyMap; - // db root - private final Map dbRoots = Maps.newConcurrentMap(); - public static String getDbEngineFromConfig(final Config config) { return config.hasPath(DB_ENGINE_CONFIG_KEY) ? config.getString(DB_ENGINE_CONFIG_KEY) : DEFAULT_DB_ENGINE; @@ -265,18 +258,6 @@ public String getCacheStrategy(CacheType dbName) { return this.cacheStrategies.getOrDefault(dbName, CacheStrategies.getCacheStrategy(dbName)); } - public Sha256Hash getDbRoot(String dbName, Sha256Hash defaultV) { - return this.dbRoots.getOrDefault(dbName, defaultV); - } - - public void setDbRoots(Config config) { - if (config.hasPath(MERKLE_ROOT)) { - config.getConfig(MERKLE_ROOT).resolve().entrySet().forEach(c -> - this.dbRoots.put(c.getKey(), Sha256Hash.wrap( - ByteString.fromHex(c.getValue().unwrapped().toString())))); - } - } - private Property createProperty(final ConfigObject conf) { Property property = new Property(); diff --git a/config/checkstyle/checkStyle.xml b/config/checkstyle/checkStyle.xml index 9d09ca11bee..16fda0fdc4f 100644 --- a/config/checkstyle/checkStyle.xml +++ b/config/checkstyle/checkStyle.xml @@ -1,7 +1,7 @@ + "http://checkstyle.sourceforge.net/dtds/configuration_1_3.dtd"> + ``` [PM2] Spawning PM2 daemon with pm2_home=/root/.pm2 [PM2] PM2 Successfully daemonized @@ -165,6 +166,25 @@ If everything goes well, your terminal console output will look like following : (8) TYjQd4xrLZQGYMdLJqsTCuXVGapPqUp9ZX (10000 TRX) (9) THCw6hPZpFcLCWDcsZg3W77rXZ9rJQPncD (10000 TRX) + Private Keys + ================== + + (0) 2b2bddbeea87cecedcaf51eef55877b65725f709d2c0fcdfea0cb52d80acd52b + (1) f08759925316dc6344af538ebe3a619aeab836a0c254adca903cc764f87b0ee9 + (2) 1afc9f033cf9c6058db366b78a9f1b9c909b1b83397c9aed795afa05e9017511 + (3) f8f5bc70e91fc177eefea43b68c97b66536ac317a9300639e9d32a9db2f18a1f + (4) 031015272915917056c117d3cc2a03491a8f22ef450af83f6783efddf7064c59 + (5) 5eb25e2c1144f216aa99bbe2139d84bb6dedfb2c1ed72f3df6684a4c6d2cd96b + (6) f0b781da23992e6a3f536cb60917c3eb6a9c5434fcf441fcb8d7c58c01d6b70e + (7) 158f60a4379688a77d4a420e2f2a3e014ebf9ed0a1a093d7dc01ba23ebc5c970 + (8) e9342bb9108f46573804890a5301530c2834dce3703cd51ab77fba6161afec00 + (9) 2e9f0c507d2ea98dc4005a1afb1b743c629f7c145ccb55f38f75ae73cf8f605c + + HD Wallet + ================== + Mnemonic: border pulse twenty cruise grief shy need raw clean possible begin climb + Base HD Path: m/44'/60'/0'/0/{account_index} + ``` diff --git a/run.md b/run.md index c0ecbe4d91f..112478a4db5 100644 --- a/run.md +++ b/run.md @@ -14,9 +14,9 @@ Use the [Testnet Config](https://github.com/tronprotocol/TronDeployment/blob/mas **Use the executable JAR(Recommended way):** ```bash -java -jar FullNode.jar -p --witness -c your config.conf(Example:/data/java-tron/config.conf) +java -jar FullNode.jar -p your private key --witness -c your config.conf(Example:/data/java-tron/config.conf) Example: -java -jar FullNode.jar -p --witness -c /data/java-tron/config.conf +java -jar FullNode.jar -p 650950B193DDDDB35B6E48912DD28F7AB0E7140C1BFDEFD493348F02295BD812 --witness -c /data/java-tron/config.conf ``` @@ -65,9 +65,9 @@ Then observe whether block synchronization success,If synchronization successf ```bash cd build/libs -java -jar FullNode.jar -p --witness -c your config.conf (Example:/data/java-tron/config.conf) +java -jar FullNode.jar -p your private key --witness -c your config.conf (Example:/data/java-tron/config.conf) Example: -java -jar FullNode.jar -p --witness -c /data/java-tron/config.conf +java -jar FullNode.jar -p 650950B193DDDDB35B6E48912DD28F7AB0E7140C1BFDEFD493348F02295BD812 --witness -c /data/java-tron/config.conf ``` @@ -81,7 +81,7 @@ java -jar FullNode.jar -p --witness -c /data/java-tron/config Using TaskInputs.file() with something that doesn't resolve to a File object has been deprecated and is scheduled to be removed in Gradle 5.0. Use TaskInputs.files() instead. > Task :run -20:39:22.749 INFO [o.t.c.c.a.Args] private.key = 63e62a71ed3... +20:39:22.749 INFO [o.t.c.c.a.Args] private.key = 63e62a71ed39e30bac7223097a173924aad5855959de517ff2987b0e0ec89f1a 20:39:22.816 WARN [o.t.c.c.a.Args] localwitness size must be one, get the first one 20:39:22.832 INFO [o.t.p.FullNode] Here is the help message.output-directory/ 三月 22, 2018 8:39:23 下午 org.tron.core.services.RpcApiService start diff --git a/script/checkStyle.sh b/script/checkStyle.sh new file mode 100644 index 00000000000..af3d5e7df1f --- /dev/null +++ b/script/checkStyle.sh @@ -0,0 +1,26 @@ +./gradlew clean build -x test > build.log 2>&1 +if [ $? != 0 ];then + echo "run ./gradlew build fail, Please check you code, Or just retry this test" + exit 1 +fi +echo "------------------------------ checkStyle check ------------------------------" +#echo $BUILDKITE_PULL_REQUEST_BASE_BRANCH +#if [[ x"$BUILDKITE_PULL_REQUEST_BASE_BRANCH" != x'develop' && x"$BUILDKITE_PULL_REQUEST_BASE_BRANCH" != x'master' ]];then +# echo "BUILDKITE_PULL_REQUEST_BASE_BRANCH isnot develop or master, SKIPED" +# exit 0 +#fi + +grep -v ":checkstyleMain\|:checkstyleTest\|:lint" build.log |grep "ant:checkstyle" > checkStyle.log 2>&1 +checkNum=`cat checkStyle.log | wc -l` +if [ ${checkNum} -gt 0 ];then + echo "please fix checkStyle problem," + echo "run [ ./gradlew clean build -x test ], and you can find checkStyle report in framework/build/reports/checkstyle/" + echo "!!!!! checkStyle Num ${checkNum} !!!!!" + cat checkStyle.log + + echo "checkStyle Failed, please fix checkStyle problem" + touch checkFailTag +else + echo "checkStyle problem zero" +fi +exit 0 diff --git a/script/codecov.sh b/script/codecov.sh new file mode 100644 index 00000000000..ba83a5a8ee2 --- /dev/null +++ b/script/codecov.sh @@ -0,0 +1,5 @@ +bash <(curl -s https://codecov.io/bash) -t ee5ed39e-1cc4-49d1-bcf9-12bce10e5b3b -s ./common/build/reports/jacoco/test/ -s ./consensus/build/reports/jacoco/test/ -s ./chainbase/build/reports/jacoco/test/ -s ./actuator/build/reports/jacoco/test/ -s ./framework/build/reports/jacoco/test/ + +#bash <(curl -s https://codecov.io/bash) -t ee5ed39e-1cc4-49d1-bcf9-12bce10e5b3b -s ./common/build/reports/jacoco/test/jacocoTestReport.xml -s ./consensus/build/reports/jacoco/test/jacocoTestReport.xml -s ./chainbase/build/reports/jacoco/test/jacocoTestReport.xml -s ./actuator/build/reports/jacoco/test/jacocoTestReport.xml -s ./framework/build/reports/jacoco/test/jacocoTestReport.xml + +#bash <(curl -s https://codecov.io/bash) -t c2f718cbe2e84c62970a892cef614689 diff --git a/script/querySonar.sh b/script/querySonar.sh new file mode 100644 index 00000000000..8c558634304 --- /dev/null +++ b/script/querySonar.sh @@ -0,0 +1,41 @@ +echo "current branch is : "$BUILDKITE_BRANCH +if [ $BUILDKITE_PULL_REQUEST = "false" ]; then + SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&branch="$BUILDKITE_BRANCH + Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` + echo "current branch sonarcloud status is : "$Status + if [ $Status = null ]; then + echo "wait for check finish, 5m ....." + sleep 300 + SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&branch="$BUILDKITE_BRANCH + Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` + fi + + if [ x"$Status" = x'"OK"' ];then + echo "Sonar Check Pass" + exit 0 + else + echo "Sonar Check Failed" + echo "Please visit https://sonarcloud.io/dashboard?branch="$BUILDKITE_BRANCH"&id=java-tron for more details" + exit 1 + fi +else + echo "current PR number is : "$BUILDKITE_PULL_REQUEST + SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&pullRequest="$BUILDKITE_PULL_REQUEST + Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` + if [ $Status = null ]; then + echo "wait for check finish, 5m ....." + sleep 300 + SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&pullRequest="$BUILDKITE_PULL_REQUEST + Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` + fi + + echo "current pullRequest sonarcloud status is : "$Status + if [ x"$Status" = x'"OK"' ];then + echo "Sonar Check Pass" + exit 0 + else + echo "Sonar Check Failed" + echo "Please visit https://sonarcloud.io/dashboard?id=java-tron&pullRequest="$BUILDKITE_PULL_REQUEST" for more details" + exit 1 + fi +fi \ No newline at end of file diff --git a/script/sonar.sh b/script/sonar.sh new file mode 100644 index 00000000000..b3e2b5ccf28 --- /dev/null +++ b/script/sonar.sh @@ -0,0 +1,89 @@ +echo "------------------------------ sonar check ------------------------------" +export SONAR_SCANNER_VERSION=4.2.0.1873 +export SONAR_SCANNER_HOME=/home/java-tron/sonar-scanner-4.1.0.1829-linux +export PATH=$SONAR_SCANNER_HOME/bin:$PATH +export SONAR_SCANNER_OPTS="-server" +#export PATH=$PATH:/home/java-tron/sonar-scanner-4.1.0.1829-linux/bin + +#BUILDKITE_BRANCH="MiraculousWang:develop" + +echo "current branch is : "$BUILDKITE_BRANCH +if [ $BUILDKITE_PULL_REQUEST = "false" ]; then + + sonar-scanner \ + -Dsonar.projectKey=java-tron \ + -Dsonar.organization=tron-zhaohong \ + -Dsonar.sources=./actuator/src,./framework/src/main,./consensus/src,./chainbase/src,./common/src,./crypto/src,./protocol/src \ + -Dsonar.java.binaries=./actuator/build/classes,./framework/build/classes,./consensus/build/classes,./chainbase/build/classes,./common/build/classes,./crypto/build/classes,./protocol/build/classes \ + -Dsonar.host.url=https://sonarcloud.io \ + -Dsonar.links.homepage=https://github.com/tronprotocol/java-tron \ + -Dsonar.links.scm=https://github.com/tronprotocol/java-tron \ + -Dsoanr.links.issue=https://github.com/tronprotocol/java-tron/issues \ + -Dsonar.branch.name=$BUILDKITE_BRANCH \ + -Dsonar.coverage.jacoco.xmlReportPaths=./common/build/reports/jacoco/test/jacocoTestReport.xml,./consensus/build/reports/jacoco/test/jacocoTestReport.xml,./chainbase/build/reports/jacoco/test/jacocoTestReport.xml,./actuator/build/reports/jacoco/test/jacocoTestReport.xml,./framework/build/reports/jacoco/test/jacocoTestReport.xml \ + -Dsonar.login=1717c3c748ec2e0ea61e501b05458de243c4abcc > /data/checkStyle/sonar.log + + sleep 100 + + + SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&branch="$BUILDKITE_BRANCH + Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` + echo "current branch sonarcloud status is : "$Status + if [ $Status = null ]; then + echo "wait for check finish, 5m ....." + sleep 300 + SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&branch="$BUILDKITE_BRANCH + Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` + fi + + if [ x"$Status" = x'"OK"' ];then + echo "Sonar Check Pass" + exit 0 + else + echo ">>>>>>>>>>>>>>>>>>>>>>>>>> Sonar Check Failed <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" + echo ">>>>>>>>>>>> Please visit https://sonarcloud.io/dashboard?branch="$BUILDKITE_BRANCH"&id=java-tron for more details <<<<<<<<<<<<<<<<<<" + touch checkFailTag + exit 0 + fi +else + echo "current PR number is : "$BUILDKITE_PULL_REQUEST + + sonar-scanner \ + -Dsonar.projectKey=java-tron \ + -Dsonar.organization=tron-zhaohong \ + -Dsonar.sources=./actuator/src,./framework/src/main,./consensus/src,./chainbase/src,./common/src,./crypto/src,./protocol/src \ + -Dsonar.java.binaries=./actuator/build/classes,./framework/build/classes,./consensus/build/classes,./chainbase/build/classes,./common/build/classes,./crypto/build/classes,./protocol/build/classes \ + -Dsonar.host.url=https://sonarcloud.io \ + -Dsonar.links.homepage=https://github.com/tronprotocol/java-tron \ + -Dsonar.links.scm=https://github.com/tronprotocol/java-tron \ + -Dsoanr.links.issue=https://github.com/tronprotocol/java-tron/issues \ + -Dsonar.pullrequest.key=$BUILDKITE_PULL_REQUEST \ + -Dsonar.pullrequest.branch=$BUILDKITE_BRANCH \ + -Dsonar.pullrequest.base=$BUILDKITE_PULL_REQUEST_BASE_BRANCH \ + -Dsonar.coverage.jacoco.xmlReportPaths=./common/build/reports/jacoco/test/jacocoTestReport.xml,./consensus/build/reports/jacoco/test/jacocoTestReport.xml,./chainbase/build/reports/jacoco/test/jacocoTestReport.xml,./actuator/build/reports/jacoco/test/jacocoTestReport.xml,./framework/build/reports/jacoco/test/jacocoTestReport.xml \ + -Dsonar.login=1717c3c748ec2e0ea61e501b05458de243c4abcc > /data/checkStyle/sonar.log + + sleep 100 + + SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&pullRequest="$BUILDKITE_PULL_REQUEST + Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` + if [ $Status = null ]; then + echo "wait for check finish, 5m ....." + sleep 300 + SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&pullRequest="$BUILDKITE_PULL_REQUEST + Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` + fi + + echo "current pullRequest sonarcloud status is : "$Status + if [ x"$Status" = x'"OK"' ];then + echo "Sonar Check Pass" + exit 0 + else + echo " -------------------------------- sonar check Failed ---------------------------------" + echo ">>>>>>>>>>>>>>> Please visit https://sonarcloud.io/dashboard?id=java-tron&pullRequest="$BUILDKITE_PULL_REQUEST" for more details <<<<<<<<<<<<<<<<<<" + echo "If this Sonar problem is not caused by your modification,Make sure you local branch is newest, And merge the newest tronprotocol/java-tron" + echo ">>>>>>>>>>>>>>>>>>>>>>>>>> Sonar Check Failed <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< " + touch checkFailTag + exit 0 + fi +fi From 089c667d5da50ccaf071b48ca0b8a7350bb78cb4 Mon Sep 17 00:00:00 2001 From: halibobo1205 <82020050+halibobo1205@users.noreply.github.com> Date: Mon, 11 Mar 2024 19:18:36 +0800 Subject: [PATCH 59/60] Revert "Revert "feat(Nile): merge release_v4.7.4 into Nile"" --- README.md | 141 ++-- Tron protobuf protocol document.md | 16 +- actuator/build.gradle | 16 - .../org/tron/core/utils/ProposalUtil.java | 23 +- build.gradle | 13 +- chainbase/build.gradle | 34 +- .../org/tron/common/utils/ForkController.java | 2 +- .../tron/core/capsule/TransactionCapsule.java | 4 +- .../tron/core/capsule/utils/MerkleTree.java | 2 + .../core/db/common/iterator/DBIterator.java | 64 +- .../db/common/iterator/RockStoreIterator.java | 64 +- .../db/common/iterator/StoreIterator.java | 61 +- .../tron/core/service/MortgageService.java | 45 +- .../tron/core/service/RewardViCalService.java | 286 ++++++++ .../core/store/DynamicPropertiesStore.java | 17 + .../org/tron/core/store/RewardViStore.java | 43 ++ common/build.gradle | 9 +- .../common/parameter/CommonParameter.java | 17 +- .../org/tron/common/utils/MerkleRoot.java | 68 ++ .../src/main/java/org/tron/core/Constant.java | 9 +- .../java/org/tron/core/config/Parameter.java | 5 +- .../org/tron/core/config/args/Storage.java | 19 + config/checkstyle/checkStyle.xml | 2 +- config/checkstyle/checkStyleAll.xml | 2 +- consensus/build.gradle | 13 - .../consensus/pbft/PbftMessageHandle.java | 4 +- crypto/build.gradle | 2 - docs/implement-a-customized-actuator-en.md | 2 +- docs/implement-a-customized-actuator-zh.md | 2 +- framework/build.gradle | 33 +- framework/config/checkstyle/checkStyle.xml | 2 +- framework/config/checkstyle/checkStyleAll.xml | 2 +- .../common/application/ApplicationImpl.java | 4 +- .../nativequeue/NativeMessageQueue.java | 6 +- .../src/main/java/org/tron/core/Wallet.java | 15 + .../java/org/tron/core/config/args/Args.java | 58 +- .../tron/core/consensus/ProposalService.java | 4 + .../main/java/org/tron/core/db/Manager.java | 10 + .../db/common/iterator/AbstractIterator.java | 41 -- .../common/iterator/AssetIssueIterator.java | 17 - .../core/db/common/iterator/DBIterator.java | 9 - .../common/iterator/TransactionIterator.java | 22 - .../db/common/iterator/WitnessIterator.java | 17 - .../org/tron/core/net/TronNetDelegate.java | 15 + .../net/message/handshake/HelloMessage.java | 29 +- .../net/messagehandler/BlockMsgHandler.java | 16 +- .../messagehandler/InventoryMsgHandler.java | 7 + .../messagehandler/PbftDataSyncHandler.java | 18 +- .../net/messagehandler/PbftMsgHandler.java | 3 + .../tron/core/net/peer/PeerConnection.java | 1 - .../service/handshake/HandshakeService.java | 15 +- .../tron/core/services/NodeInfoService.java | 2 +- .../org/tron/core/services/RpcApiService.java | 18 +- .../org/tron/core/services/http/Util.java | 2 +- .../interfaceOnPBFT/RpcApiServiceOnPBFT.java | 5 + .../RpcApiServiceOnSolidity.java | 5 + .../org/tron/tool/litefullnode/DbTool.java | 199 ------ .../tool/litefullnode/LiteFullNodeTool.java | 637 ------------------ .../java/org/tron/tool/litefullnode/README.md | 109 --- .../java/org/tron/tool/litefullnode/Util.java | 62 -- .../tool/litefullnode/db/DBInterface.java | 21 - .../tool/litefullnode/db/LevelDBImpl.java | 46 -- .../tool/litefullnode/db/RocksDBImpl.java | 66 -- .../litefullnode/iterator/DBIterator.java | 18 - .../iterator/LevelDBIterator.java | 47 -- .../litefullnode/iterator/RockDBIterator.java | 48 -- .../src/main/resources/config-backup.conf | 1 - framework/src/main/resources/config-beta.conf | 1 - .../src/main/resources/config-localtest.conf | 4 +- .../src/main/resources/config-test-net.conf | 1 - framework/src/main/resources/config.conf | 13 +- .../org/tron/common/config/args/ArgsTest.java | 1 + .../tron/common/jetty/JettyServerTest.java | 63 ++ .../core/actuator/ActuatorFactoryTest.java | 71 ++ .../core/actuator/utils/ProposalUtilTest.java | 57 +- .../actuator/utils/TransactionUtilTest.java | 19 + .../core/capsule/utils/DecodeResultTest.java | 28 + .../core/capsule/utils/MerkleTreeTest.java | 35 +- .../tron/core/capsule/utils/RLPListTest.java | 81 +++ .../org/tron/core/config/args/ArgsTest.java | 32 +- .../tron/core/db/AccountTraceStoreTest.java | 13 + .../org/tron/core/db/BlockIndexStoreTest.java | 64 ++ .../java/org/tron/core/db/BlockStoreTest.java | 69 ++ .../java/org/tron/core/db/DBIteratorTest.java | 110 ++- .../core/db/DelegatedResourceStoreTest.java | 15 + .../org/tron/core/db/DelegationStoreTest.java | 17 + .../org/tron/core/db/ExchangeStoreTest.java | 25 + .../org/tron/core/db/ExchangeV2StoreTest.java | 26 + .../tron/core/db/MarketAccountStoreTest.java | 16 + .../tron/core/db/MarketOrderStoreTest.java | 17 + .../tron/core/db/RecentBlockStoreTest.java | 81 +++ .../core/db/RecentTransactionStoreTest.java | 72 ++ .../tron/core/db/TransactionHistoryTest.java | 7 + .../tron/core/db/TransactionStoreTest.java | 2 +- .../org/tron/core/db/ZKProofStoreTest.java | 58 ++ .../tron/core/net/TronNetDelegateTest.java | 52 ++ .../InventoryMsgHandlerTest.java | 22 +- .../PbftDataSyncHandlerTest.java | 7 +- .../messagehandler/PbftMsgHandlerTest.java | 9 + .../net/services/HandShakeServiceTest.java | 45 ++ .../net/services/TronStatsManagerTest.java | 27 + .../java/org/tron/core/pbft/PbftTest.java | 1 + .../tron/core/services/ComputeRewardTest.java | 307 +++++++++ .../core/services/RpcApiServicesTest.java | 6 +- .../LiteFnQueryGrpcInterceptorTest.java | 6 +- .../filter/RpcApiAccessInterceptorTest.java | 6 +- .../services/http/ClearABIServletTest.java | 92 +++ .../http/CreateAccountServletTest.java | 75 +++ .../http/CreateAssetIssueServletTest.java | 90 +++ .../http/CreateSpendAuthSigServletTest.java | 60 ++ .../http/CreateWitnessServletTest.java | 88 +++ .../http/GetAccountByIdServletTest.java | 47 ++ .../http/GetBlockByIdServletTest.java | 51 ++ .../http/GetBlockByNumServletTest.java | 69 ++ ...tTransactionInfoByBlockNumServletTest.java | 79 +++ .../GetTransactionInfoByIdServletTest.java | 126 ++++ ...TransactionListFromPendingServletTest.java | 38 ++ .../http/UpdateAccountServletTest.java | 77 +++ .../services/jsonrpc/BlockResultTest.java | 46 ++ .../services/jsonrpc/BuildArgumentsTest.java | 73 ++ .../services/jsonrpc/CallArgumentsTest.java | 47 ++ .../jsonrpc/TransactionReceiptTest.java | 66 ++ .../jsonrpc/TransactionResultTest.java | 59 ++ .../tron/core/zksnark/NoteEncDecryTest.java | 2 - .../core/zksnark/ShieldedReceiveTest.java | 5 +- .../tron/program/LiteFullNodeToolTest.java | 202 ------ framework/src/test/resources/args-test.conf | 224 ++++++ .../src/test/resources/config-localtest.conf | 14 +- .../test/resources/config-test-dbbackup.conf | 1 - .../src/test/resources/config-test-index.conf | 1 - .../test/resources/config-test-mainnet.conf | 1 - .../resources/config-test-storagetest.conf | 3 +- framework/src/test/resources/config-test.conf | 10 +- plugins/README.md | 12 +- plugins/build.gradle | 3 - .../src/main/java/org/tron/plugins/Db.java | 3 +- .../main/java/org/tron/plugins/DbRoot.java | 121 ++++ .../org/tron/plugins/utils/MerkleRoot.java | 68 ++ .../org/tron/plugins/utils/Sha256Hash.java | 10 +- .../tron/plugins/utils/db/DBInterface.java | 2 + .../org/tron/plugins/utils/db/DbTool.java | 18 +- .../tron/plugins/utils/db/LevelDBImpl.java | 7 +- .../tron/plugins/utils/db/RocksDBImpl.java | 7 +- .../java/org/tron/plugins/DbLiteTest.java | 6 +- .../java/org/tron/plugins/DbRootTest.java | 82 +++ protocol/build.gradle | 2 + protocol/src/main/protos/api/api.proto | 2 + protocol/src/main/protos/core/Tron.proto | 1 + quickstart.md | 20 - run.md | 10 +- script/checkStyle.sh | 26 - script/codecov.sh | 5 - script/querySonar.sh | 41 -- script/sonar.sh | 89 --- 154 files changed, 4141 insertions(+), 2141 deletions(-) create mode 100644 chainbase/src/main/java/org/tron/core/service/RewardViCalService.java create mode 100755 chainbase/src/main/java/org/tron/core/store/RewardViStore.java create mode 100644 common/src/main/java/org/tron/common/utils/MerkleRoot.java delete mode 100644 framework/src/main/java/org/tron/core/db/common/iterator/AbstractIterator.java delete mode 100644 framework/src/main/java/org/tron/core/db/common/iterator/AssetIssueIterator.java delete mode 100755 framework/src/main/java/org/tron/core/db/common/iterator/DBIterator.java delete mode 100644 framework/src/main/java/org/tron/core/db/common/iterator/TransactionIterator.java delete mode 100644 framework/src/main/java/org/tron/core/db/common/iterator/WitnessIterator.java delete mode 100644 framework/src/main/java/org/tron/tool/litefullnode/DbTool.java delete mode 100644 framework/src/main/java/org/tron/tool/litefullnode/LiteFullNodeTool.java delete mode 100644 framework/src/main/java/org/tron/tool/litefullnode/README.md delete mode 100644 framework/src/main/java/org/tron/tool/litefullnode/Util.java delete mode 100644 framework/src/main/java/org/tron/tool/litefullnode/db/DBInterface.java delete mode 100644 framework/src/main/java/org/tron/tool/litefullnode/db/LevelDBImpl.java delete mode 100644 framework/src/main/java/org/tron/tool/litefullnode/db/RocksDBImpl.java delete mode 100644 framework/src/main/java/org/tron/tool/litefullnode/iterator/DBIterator.java delete mode 100644 framework/src/main/java/org/tron/tool/litefullnode/iterator/LevelDBIterator.java delete mode 100644 framework/src/main/java/org/tron/tool/litefullnode/iterator/RockDBIterator.java create mode 100644 framework/src/test/java/org/tron/common/jetty/JettyServerTest.java create mode 100644 framework/src/test/java/org/tron/core/actuator/ActuatorFactoryTest.java create mode 100644 framework/src/test/java/org/tron/core/capsule/utils/DecodeResultTest.java create mode 100644 framework/src/test/java/org/tron/core/capsule/utils/RLPListTest.java create mode 100644 framework/src/test/java/org/tron/core/db/BlockIndexStoreTest.java create mode 100644 framework/src/test/java/org/tron/core/db/RecentBlockStoreTest.java create mode 100644 framework/src/test/java/org/tron/core/db/RecentTransactionStoreTest.java create mode 100644 framework/src/test/java/org/tron/core/db/ZKProofStoreTest.java create mode 100644 framework/src/test/java/org/tron/core/net/TronNetDelegateTest.java create mode 100644 framework/src/test/java/org/tron/core/net/services/TronStatsManagerTest.java create mode 100644 framework/src/test/java/org/tron/core/services/ComputeRewardTest.java create mode 100644 framework/src/test/java/org/tron/core/services/http/ClearABIServletTest.java create mode 100644 framework/src/test/java/org/tron/core/services/http/CreateAccountServletTest.java create mode 100644 framework/src/test/java/org/tron/core/services/http/CreateAssetIssueServletTest.java create mode 100644 framework/src/test/java/org/tron/core/services/http/CreateSpendAuthSigServletTest.java create mode 100644 framework/src/test/java/org/tron/core/services/http/CreateWitnessServletTest.java create mode 100644 framework/src/test/java/org/tron/core/services/http/GetAccountByIdServletTest.java create mode 100644 framework/src/test/java/org/tron/core/services/http/GetBlockByIdServletTest.java create mode 100644 framework/src/test/java/org/tron/core/services/http/GetBlockByNumServletTest.java create mode 100644 framework/src/test/java/org/tron/core/services/http/GetTransactionInfoByBlockNumServletTest.java create mode 100644 framework/src/test/java/org/tron/core/services/http/GetTransactionInfoByIdServletTest.java create mode 100644 framework/src/test/java/org/tron/core/services/http/GetTransactionListFromPendingServletTest.java create mode 100644 framework/src/test/java/org/tron/core/services/http/UpdateAccountServletTest.java create mode 100644 framework/src/test/java/org/tron/core/services/jsonrpc/BlockResultTest.java create mode 100644 framework/src/test/java/org/tron/core/services/jsonrpc/BuildArgumentsTest.java create mode 100644 framework/src/test/java/org/tron/core/services/jsonrpc/CallArgumentsTest.java create mode 100644 framework/src/test/java/org/tron/core/services/jsonrpc/TransactionReceiptTest.java create mode 100644 framework/src/test/java/org/tron/core/services/jsonrpc/TransactionResultTest.java delete mode 100644 framework/src/test/java/org/tron/program/LiteFullNodeToolTest.java create mode 100644 framework/src/test/resources/args-test.conf create mode 100644 plugins/src/main/java/org/tron/plugins/DbRoot.java create mode 100644 plugins/src/main/java/org/tron/plugins/utils/MerkleRoot.java create mode 100644 plugins/src/test/java/org/tron/plugins/DbRootTest.java delete mode 100644 script/checkStyle.sh delete mode 100644 script/codecov.sh delete mode 100644 script/querySonar.sh delete mode 100644 script/sonar.sh diff --git a/README.md b/README.md index 4d1d7b0b3b6..89101bbc4d1 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,6 @@ Java implementation of the Tron Protocol -

@@ -42,6 +41,7 @@

## Table of Contents + - [What’s TRON?](#whats-tron) - [Building the Source Code](#building-the-source) - [Running java-tron](#running-java-tron) @@ -55,94 +55,109 @@ TRON is a project dedicated to building the infrastructure for a truly decentralized Internet. -* Tron Protocol, one of the largest blockchain-based operating systems in the world, offers scalable, high-availability and high-throughput support that underlies all the decentralized applications in the TRON ecosystem. +- Tron Protocol, one of the largest blockchain-based operating systems in the world, offers scalable, high-availability and high-throughput support that underlies all the decentralized applications in the TRON ecosystem. -* Tron Virtual Machine (TVM) allows anyone to develop decentralized applications (DAPPs) for themselves or their communities with smart contracts thereby making decentralized crowdfunding and token issuance easier than ever. +- Tron Virtual Machine (TVM) allows anyone to develop decentralized applications (DAPPs) for themselves or their communities with smart contracts thereby making decentralized crowdfunding and token issuance easier than ever. TRON enables large-scale development and engagement. With over 2000 transactions per second (TPS), high concurrency, low latency, and massive data transmission. It is ideal for building decentralized entertainment applications. Free features and incentive systems allow developers to create premium app experiences for users. # Building the source + Building java-tron requires `git` and 64-bit version of `Oracle JDK 1.8` to be installed, other JDK versions are not supported yet. Make sure you operate on `Linux` and `MacOS` operating systems. Clone the repo and switch to the `master` branch - ```bash - $ git clone https://github.com/tronprotocol/java-tron.git - $ cd java-tron - $ git checkout -t origin/master - ``` +```bash +$ git clone https://github.com/tronprotocol/java-tron.git +$ cd java-tron +$ git checkout -t origin/master +``` + then run the following command to build java-tron, the `FullNode.jar` file can be found in `java-tron/build/libs/` after build successful. + ```bash $ ./gradlew clean build -x test ``` - # Running java-tron + Running java-tron requires 64-bit version of `Oracle JDK 1.8` to be installed, other JDK versions are not supported yet. Make sure you operate on `Linux` and `MacOS` operating systems. -Get the mainnet configuration file: [main_net_config.conf](https://github.com/tronprotocol/tron-deployment/blob/master/main_net_config.conf), other network configuration files can be find [here](https://github.com/tronprotocol/tron-deployment). +Get the mainnet configuration file: [main_net_config.conf](https://github.com/tronprotocol/tron-deployment/blob/master/main_net_config.conf), other network configuration files can be found [here](https://github.com/tronprotocol/tron-deployment). + ## Hardware Requirements + Minimum: -* CPU with 8 cores -* 16GB RAM -* 2TB free storage space to sync the Mainnet + +- CPU with 8 cores +- 16GB RAM +- 2TB free storage space to sync the Mainnet Recommended: -* CPU with 16+ cores(32+ cores for a super representative) -* 32GB+ RAM(64GB+ for a super representative) -* High Performance SSD with at least 2.5TB free space -* 100+ MB/s download Internet service +- CPU with 16+ cores(32+ cores for a super representative) +- 32GB+ RAM(64GB+ for a super representative) +- High Performance SSD with at least 2.5TB free space +- 100+ MB/s download Internet service ## Running a full node for mainnet -Full node has full historical data, it is the entry point into the TRON network , it can be used by other processes as a gateway into the TRON network via HTTP and GRPC endpoints. You can interact with the TRON network through full node:transfer assets, deploy contracts, interact with contracts and so on. `-c ` parameter specifies a configuration file to run a full node: - ```bash - $ nohup java -Xms9G -Xmx9G -XX:ReservedCodeCacheSize=256m \ - -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m \ - -XX:MaxDirectMemorySize=1G -XX:+PrintGCDetails \ - -XX:+PrintGCDateStamps -Xloggc:gc.log \ - -XX:+UseConcMarkSweepGC -XX:NewRatio=2 \ - -XX:+CMSScavengeBeforeRemark -XX:+ParallelRefProcEnabled \ - -XX:+HeapDumpOnOutOfMemoryError \ - -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 \ - -jar FullNode.jar -c main_net_config.conf >> start.log 2>&1 & - ``` + +Full node has full historical data, it is the entry point into the TRON network , it can be used by other processes as a gateway into the TRON network via HTTP and GRPC endpoints. You can interact with the TRON network through full node:transfer assets, deploy contracts, interact with contracts and so on. `-c` parameter specifies a configuration file to run a full node: + +```bash +$ nohup java -Xms9G -Xmx9G -XX:ReservedCodeCacheSize=256m \ + -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m \ + -XX:MaxDirectMemorySize=1G -XX:+PrintGCDetails \ + -XX:+PrintGCDateStamps -Xloggc:gc.log \ + -XX:+UseConcMarkSweepGC -XX:NewRatio=2 \ + -XX:+CMSScavengeBeforeRemark -XX:+ParallelRefProcEnabled \ + -XX:+HeapDumpOnOutOfMemoryError \ + -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 \ + -jar FullNode.jar -c main_net_config.conf >> start.log 2>&1 & +``` + ## Running a super representative node for mainnet -Adding the `--witness` parameter to the startup command, full node will run as a super representative node. The super representative node supports all the functions of the full node and also supports block production. Before running, make sure you have a super representative account and get votes from others,once the number of obtained votes ranks in the top 27, your super representative node will participate in block production. -Fill in the private key of super representative address into the `localwitness` list in the `main_net_config.conf`, here is an example: - ``` - localwitness = [ - 650950B193DDDDB35B6E48912DD28F7AB0E7140C1BFDEFD493348F02295BD812 - ] - ``` +Adding the `--witness` parameter to the startup command, full node will run as a super representative node. The super representative node supports all the functions of the full node and also supports block production. Before running, make sure you have a super representative account and get votes from others. Once the number of obtained votes ranks in the top 27, your super representative node will participate in block production. + +Fill in the private key of super representative address into the `localwitness` list in the `main_net_config.conf`. Here is an example: + +``` + localwitness = [ + + ] +``` then run the following command to start the node: - ```bash - $ nohup java -Xms9G -Xmx9G -XX:ReservedCodeCacheSize=256m \ - -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m \ - -XX:MaxDirectMemorySize=1G -XX:+PrintGCDetails \ - -XX:+PrintGCDateStamps -Xloggc:gc.log \ - -XX:+UseConcMarkSweepGC -XX:NewRatio=2 \ - -XX:+CMSScavengeBeforeRemark -XX:+ParallelRefProcEnabled \ - -XX:+HeapDumpOnOutOfMemoryError \ - -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 \ - -jar FullNode.jar --witness -c main_net_config.conf >> start.log 2>&1 & - ``` + +```bash +$ nohup java -Xms9G -Xmx9G -XX:ReservedCodeCacheSize=256m \ + -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m \ + -XX:MaxDirectMemorySize=1G -XX:+PrintGCDetails \ + -XX:+PrintGCDateStamps -Xloggc:gc.log \ + -XX:+UseConcMarkSweepGC -XX:NewRatio=2 \ + -XX:+CMSScavengeBeforeRemark -XX:+ParallelRefProcEnabled \ + -XX:+HeapDumpOnOutOfMemoryError \ + -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 \ + -jar FullNode.jar --witness -c main_net_config.conf >> start.log 2>&1 & +``` ## Quick Start Tool -An easier way to build and run java-tron is to use `start.sh`, `start.sh` is a quick start script written in shell language, you can use it to build and run java-tron quickly and easily. + +An easier way to build and run java-tron is to use `start.sh`. `start.sh` is a quick start script written in the Shell language. You can use it to build and run java-tron quickly and easily. Here are some common use cases of the scripting tool -* Use `start.sh` to start a full node with the downloaded `FullNode.jar` -* Use `start.sh` to download the latest `FullNode.jar` and start a full node. -* Use `start.sh` to download the latest source code and compile a `FullNode.jar` and then start a full node. + +- Use `start.sh` to start a full node with the downloaded `FullNode.jar` +- Use `start.sh` to download the latest `FullNode.jar` and start a full node. +- Use `start.sh` to download the latest source code and compile a `FullNode.jar` and then start a full node. For more details, please refer to the tool [guide](./shell.md). ## Run inside Docker container One of the quickest ways to get `java-tron` up and running on your machine is by using Docker: + ```shell $ docker run -d --name="java-tron" \ -v /your_path/output-directory:/java-tron/output-directory \ @@ -155,6 +170,7 @@ $ docker run -d --name="java-tron" \ This will mount the `output-directory` and `logs` directories on the host, the docker.sh tool can also be used to simplify the use of docker, see more [here](docker/docker.md). # Community + [Tron Developers & SRs](https://discord.gg/hqKvyAM) is Tron's official Discord channel. Feel free to join this channel if you have any questions. [Core Devs Community](https://t.me/troncoredevscommunity) is the Telegram channel for java-tron community developers. If you want to contribute to java-tron, please join this channel. @@ -162,22 +178,27 @@ This will mount the `output-directory` and `logs` directories on the host, the d [tronprotocol/allcoredev](https://gitter.im/tronprotocol/allcoredev) is the official Gitter channel for developers. # Contribution -Thank you for considering to help out with the source code! If you'd like to contribute to java-tron, please see the [Contribution Guide](./CONTRIBUTING.md) for more details. +Thank you for considering to help out with the source code! If you'd like to contribute to java-tron, please see the [Contribution Guide](./CONTRIBUTING.md) for more details. # Resources -* [Medium](https://medium.com/@coredevs) java-tron's official technical articles are published there. -* [Documentation](https://tronprotocol.github.io/documentation-en/introduction/) java-tron's official technical documentation website. -* [Test network](http://nileex.io/) A stable test network of TRON contributed by TRON community. -* [Tronscan](https://tronscan.org/#/) TRON network blockchain browser. -* [Wallet-cli](https://github.com/tronprotocol/wallet-cli) TRON network wallet using command line. -* [TIP](https://github.com/tronprotocol/tips) TRON Improvement Proposal (TIP) describes standards for the TRON network. -* [TP](https://github.com/tronprotocol/tips/tree/master/tp) TRON Protocol (TP) describes standards already implemented in TRON network but not published as a TIP. + +- [Medium](https://medium.com/@coredevs) java-tron's official technical articles are published there. +- [Documentation](https://tronprotocol.github.io/documentation-en/introduction/) java-tron's official technical documentation website. +- [Test network](http://nileex.io/) A stable test network of TRON contributed by TRON community. +- [Tronscan](https://tronscan.org/#/) TRON network blockchain browser. +- [Wallet-cli](https://github.com/tronprotocol/wallet-cli) TRON network wallet using command line. +- [TIP](https://github.com/tronprotocol/tips) TRON Improvement Proposal (TIP) describes standards for the TRON network. +- [TP](https://github.com/tronprotocol/tips/tree/master/tp) TRON Protocol (TP) describes standards already implemented in TRON network but not published as a TIP. + # Integrity Check -* After January 3, 2023, releases are signed the gpg key: + +- After January 3, 2023, the release files will be signed using a GPG key pair, and the correctness of the signature will be verified using the following public key: ``` pub: 1254 F859 D2B1 BD9F 66E7 107D F859 BCB4 4A28 290B uid: build@tron.network ``` + # License + java-tron is released under the [LGPLv3 license](https://github.com/tronprotocol/java-tron/blob/master/LICENSE). diff --git a/Tron protobuf protocol document.md b/Tron protobuf protocol document.md index 852ff313797..2ba2c3113a3 100644 --- a/Tron protobuf protocol document.md +++ b/Tron protobuf protocol document.md @@ -546,11 +546,11 @@ Transaction and transaction-related messages. message `raw` - `ref_block_bytes`: Deprecated. + `ref_block_bytes`: intercepted part of the now block bytes in transaction head. - `ref_block_num`: now block number in transaction head. + `ref_block_num`: Deprecated. - `ref_block_hash`: now block hash in transaction head. + `ref_block_hash`:intercepted part of the now block hash in transaction head.. `expiration`: the expiration time in transaction head. @@ -565,15 +565,15 @@ Transaction and transaction-related messages. ```java message raw { bytes ref_block_bytes = 1; - int64 ref_block_num = 3; + int64 ref_block_num = 3; bytes ref_block_hash = 4; - int64 expiration = 8; + int64 expiration = 8; repeated authority auths = 9; - bytes data = 10; + bytes data = 10; repeated Contract contract = 11; - bytes scripts = 12; + bytes scripts = 12; int64 timestamp = 14; - int64 fee_limit = 18; + int64 fee_limit = 18; } ``` diff --git a/actuator/build.gradle b/actuator/build.gradle index a0ce72b0ee6..9b200064fb0 100644 --- a/actuator/build.gradle +++ b/actuator/build.gradle @@ -1,25 +1,9 @@ description = "actuator – a series of transactions for blockchain." -// Dependency versions -// --------------------------------------- - -def junitVersion = "4.13.2" -def mockitoVersion = "2.1.0" -def testNgVersion = "6.11" -def slf4jVersion = "1.7.25" -// -------------------------------------- - dependencies { compile project(":chainbase") compile project(":protocol") compile project(":crypto") - testImplementation "junit:junit:$junitVersion" - testImplementation "org.mockito:mockito-core:$mockitoVersion" - - compile "org.slf4j:jcl-over-slf4j:$slf4jVersion" - compile group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.69' - compile group: 'commons-codec', name: 'commons-codec', version: '1.11' - compile 'org.reflections:reflections:0.9.11' } test { diff --git a/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java b/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java index 35899284c3a..ae01f4834a9 100644 --- a/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java +++ b/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java @@ -727,6 +727,26 @@ public static void validator(DynamicPropertiesStore dynamicPropertiesStore, } break; } + case ALLOW_OLD_REWARD_OPT: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_7_4)) { + throw new ContractValidateException( + "Bad chain parameter id [ALLOW_OLD_REWARD_OPT]"); + } + if (dynamicPropertiesStore.allowOldRewardOpt()) { + throw new ContractValidateException( + "[ALLOW_OLD_REWARD_OPT] has been valid, no need to propose again"); + } + if (value != 1) { + throw new ContractValidateException( + "This value[ALLOW_OLD_REWARD_OPT] is only allowed to be 1"); + } + if (!dynamicPropertiesStore.useNewRewardAlgorithm()) { + throw new ContractValidateException( + "[ALLOW_NEW_REWARD] or [ALLOW_TVM_VOTE] proposal must be approved " + + "before [ALLOW_OLD_REWARD_OPT] can be proposed"); + } + break; + } default: break; } @@ -802,7 +822,8 @@ public enum ProposalType { // current value, value range DYNAMIC_ENERGY_MAX_FACTOR(75), // 0, [0, 100_000] ALLOW_TVM_SHANGHAI(76), // 0, 1 ALLOW_CANCEL_ALL_UNFREEZE_V2(77), // 0, 1 - MAX_DELEGATE_LOCK_PERIOD(78); // (86400, 10512000] + MAX_DELEGATE_LOCK_PERIOD(78), // (86400, 10512000] + ALLOW_OLD_REWARD_OPT(79); // 0, 1 private long code; diff --git a/build.gradle b/build.gradle index 8aad8910153..a56be97afa1 100644 --- a/build.gradle +++ b/build.gradle @@ -38,12 +38,7 @@ subprojects { dependencies { compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25' compile group: 'org.slf4j', name: 'jcl-over-slf4j', version: '1.7.25' - compile "org.slf4j:jcl-over-slf4j:1.7.25" compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.9' - compileOnly 'org.projectlombok:lombok:1.18.12' - annotationProcessor 'org.projectlombok:lombok:1.18.12' - testCompileOnly 'org.projectlombok:lombok:1.18.12' - testAnnotationProcessor 'org.projectlombok:lombok:1.18.12' compile group: 'com.google.guava', name: 'guava', version: '30.1-jre' compile "com.google.code.findbugs:jsr305:3.0.0" compile group: 'org.springframework', name: 'spring-context', version: '5.3.18' @@ -52,7 +47,15 @@ subprojects { compile group: 'org.apache.commons', name: 'commons-math', version: '2.2' compile "org.apache.commons:commons-collections4:4.1" compile group: 'joda-time', name: 'joda-time', version: '2.3' + compile group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.69' + + compileOnly 'org.projectlombok:lombok:1.18.12' + annotationProcessor 'org.projectlombok:lombok:1.18.12' + testCompileOnly 'org.projectlombok:lombok:1.18.12' + testAnnotationProcessor 'org.projectlombok:lombok:1.18.12' + testImplementation group: 'junit', name: 'junit', version: '4.13.2' + testImplementation "org.mockito:mockito-core:2.13.0" } task sourcesJar(type: Jar, dependsOn: classes) { diff --git a/chainbase/build.gradle b/chainbase/build.gradle index a2868aa78b4..408fe56ba42 100644 --- a/chainbase/build.gradle +++ b/chainbase/build.gradle @@ -2,46 +2,16 @@ description = "chainbase – a decentralized database for blockchain." // Dependency versions // --------------------------------------- - -def junitVersion = "4.13.2" -def mockitoVersion = "2.1.0" -def testNgVersion = "6.11" def jacocoVersion = "0.8.0" -def leveldbVersion = "1.8" def jansiVersion = "1.16" // -------------------------------------- -static def isWindows() { - return org.gradle.internal.os.OperatingSystem.current().isWindows() -} - -if (isWindows()) { - ext { - leveldbGroup = "org.ethereum" - leveldbName = "leveldbjni-all" - leveldbVersion = "1.18.3" - } -} else { - ext { - leveldbGroup = "org.fusesource.leveldbjni" - leveldbName = "leveldbjni-all" - leveldbVersion = "1.8" - } -} - dependencies { - testImplementation "junit:junit:$junitVersion" - testImplementation "org.mockito:mockito-core:$mockitoVersion" - - compile group: leveldbGroup, name: leveldbName, version: leveldbVersion - compile "org.fusesource.jansi:jansi:$jansiVersion" - compile group: 'org.rocksdb', name: 'rocksdbjni', version: '5.15.10' - compile group: 'com.typesafe', name: 'config', version: '1.3.2' - compile 'io.github.tronprotocol:zksnark-java-sdk:1.0.0' - compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.8.5' compile project(":protocol") compile project(":common") compile project(":crypto") + compile "org.fusesource.jansi:jansi:$jansiVersion" + compile 'io.github.tronprotocol:zksnark-java-sdk:1.0.0' compile 'org.reflections:reflections:0.9.11' } diff --git a/chainbase/src/main/java/org/tron/common/utils/ForkController.java b/chainbase/src/main/java/org/tron/common/utils/ForkController.java index c3db883a011..7cbac28e781 100644 --- a/chainbase/src/main/java/org/tron/common/utils/ForkController.java +++ b/chainbase/src/main/java/org/tron/common/utils/ForkController.java @@ -78,7 +78,7 @@ private boolean passOld(int version) { private boolean passNew(int version) { ForkBlockVersionEnum versionEnum = ForkBlockVersionEnum.getForkBlockVersionEnum(version); if (versionEnum == null) { - logger.error("Not exist block version: {}.", version); + logger.warn("Not exist block version: {}.", version); return false; } long latestBlockTime = manager.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp(); diff --git a/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java index 9598fd99a6b..a588b28c748 100755 --- a/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java @@ -102,7 +102,6 @@ public class TransactionCapsule implements ProtoCapsule { @Setter private TransactionTrace trxTrace; - private StringBuilder toStringBuff = new StringBuilder(); @Getter @Setter private long time; @@ -738,8 +737,7 @@ public Transaction getInstance() { @Override public String toString() { - - toStringBuff.setLength(0); + StringBuilder toStringBuff = new StringBuilder(); toStringBuff.append("TransactionCapsule \n[ "); toStringBuff.append("hash=").append(getTransactionId()).append("\n"); diff --git a/chainbase/src/main/java/org/tron/core/capsule/utils/MerkleTree.java b/chainbase/src/main/java/org/tron/core/capsule/utils/MerkleTree.java index 47ac45c9fb8..94d22f4b474 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/utils/MerkleTree.java +++ b/chainbase/src/main/java/org/tron/core/capsule/utils/MerkleTree.java @@ -5,10 +5,12 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; import lombok.Getter; +import net.jcip.annotations.NotThreadSafe; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.Sha256Hash; @Getter +@NotThreadSafe public class MerkleTree { private static volatile MerkleTree instance; diff --git a/chainbase/src/main/java/org/tron/core/db/common/iterator/DBIterator.java b/chainbase/src/main/java/org/tron/core/db/common/iterator/DBIterator.java index f706623693f..afbacac35db 100755 --- a/chainbase/src/main/java/org/tron/core/db/common/iterator/DBIterator.java +++ b/chainbase/src/main/java/org/tron/core/db/common/iterator/DBIterator.java @@ -1,9 +1,71 @@ package org.tron.core.db.common.iterator; +import com.google.common.collect.Iterators; +import com.google.common.collect.UnmodifiableIterator; +import com.google.common.primitives.Bytes; import java.io.Closeable; import java.util.Iterator; import java.util.Map.Entry; +import java.util.NoSuchElementException; -public interface DBIterator extends Iterator>, Closeable { +public interface DBIterator extends Iterator>, AutoCloseable, Closeable { + void seek(byte[] key); + + void seekToFirst(); + + void seekToLast(); + + /** + * An iterator is either positioned at a key/value pair, or + * not valid. This method returns true iff the iterator is valid. + * + * REQUIRES: iterator not closed + * + * @throws IllegalStateException if the iterator is closed. + * @return an iterator is either positioned at a key/value pair + */ + boolean valid(); + + /** + * The underlying storage for + * the returned slice is valid only until the next modification of + * the iterator. + * + * REQUIRES: valid() && !closed + * + * @throws IllegalStateException if the iterator is closed. + * @throws NoSuchElementException if the iterator is not valid. + * + * @return the key for the current entry + */ + byte[] getKey(); + + /** + * The underlying storage for + * the returned slice is valid only until the next modification of + * the iterator. + * + * REQUIRES: valid() && !closed + * + * @throws IllegalStateException if the iterator is closed. + * @throws NoSuchElementException if the iterator is not valid. + * + * @return the value for the current entry + */ + byte[] getValue(); + + /** + * @throws IllegalStateException if the iterator is closed. + */ + void checkState(); + + /** + * @throws NoSuchElementException if the iterator is not valid. + */ + default void checkValid() { + if (!valid()) { + throw new NoSuchElementException(); + } + } } diff --git a/chainbase/src/main/java/org/tron/core/db/common/iterator/RockStoreIterator.java b/chainbase/src/main/java/org/tron/core/db/common/iterator/RockStoreIterator.java index a8c4cff2066..541f71348af 100644 --- a/chainbase/src/main/java/org/tron/core/db/common/iterator/RockStoreIterator.java +++ b/chainbase/src/main/java/org/tron/core/db/common/iterator/RockStoreIterator.java @@ -3,6 +3,7 @@ import java.io.IOException; import java.util.Map.Entry; import java.util.NoSuchElementException; +import java.util.concurrent.atomic.AtomicBoolean; import lombok.extern.slf4j.Slf4j; import org.rocksdb.RocksIterator; @@ -13,7 +14,7 @@ public final class RockStoreIterator implements DBIterator { private final RocksIterator dbIterator; private boolean first = true; - private boolean valid = true; + private final AtomicBoolean close = new AtomicBoolean(false); public RockStoreIterator(RocksIterator dbIterator) { this.dbIterator = dbIterator; @@ -21,12 +22,14 @@ public RockStoreIterator(RocksIterator dbIterator) { @Override public void close() throws IOException { - dbIterator.close(); + if (close.compareAndSet(false, true)) { + dbIterator.close(); + } } @Override public boolean hasNext() { - if (!valid) { + if (close.get()) { return false; } boolean hasNext = false; @@ -37,13 +40,12 @@ public boolean hasNext() { first = false; } if (!(hasNext = dbIterator.isValid())) { // false is last item - dbIterator.close(); - valid = false; + close(); } } catch (Exception e) { logger.error(e.getMessage(), e); try { - dbIterator.close(); + close(); } catch (Exception e1) { logger.error(e.getMessage(), e); } @@ -53,7 +55,7 @@ public boolean hasNext() { @Override public Entry next() { - if (!valid) { + if (close.get()) { throw new NoSuchElementException(); } byte[] key = dbIterator.key(); @@ -76,4 +78,50 @@ public byte[] setValue(byte[] value) { } }; } -} \ No newline at end of file + + @Override + public void seek(byte[] key) { + checkState(); + dbIterator.seek(key); + this.first = false; + } + + @Override + public void seekToFirst() { + checkState(); + dbIterator.seekToFirst(); + this.first = false; + } + + @Override + public void seekToLast() { + checkState(); + dbIterator.seekToLast(); + this.first = false; + } + + @Override + public boolean valid() { + checkState(); + return dbIterator.isValid(); + } + + @Override + public byte[] getKey() { + checkValid(); + return dbIterator.key(); + } + + @Override + public byte[] getValue() { + checkValid(); + return dbIterator.value(); + } + + @Override + public void checkState() { + if (close.get()) { + throw new IllegalStateException("iterator has been closed"); + } + } +} diff --git a/chainbase/src/main/java/org/tron/core/db/common/iterator/StoreIterator.java b/chainbase/src/main/java/org/tron/core/db/common/iterator/StoreIterator.java index 292bb421e54..d771716a7e8 100755 --- a/chainbase/src/main/java/org/tron/core/db/common/iterator/StoreIterator.java +++ b/chainbase/src/main/java/org/tron/core/db/common/iterator/StoreIterator.java @@ -3,6 +3,7 @@ import java.io.IOException; import java.util.Map.Entry; import java.util.NoSuchElementException; +import java.util.concurrent.atomic.AtomicBoolean; import lombok.extern.slf4j.Slf4j; import org.iq80.leveldb.DBIterator; @@ -13,7 +14,7 @@ public final class StoreIterator implements org.tron.core.db.common.iterator.DBI private final DBIterator dbIterator; private boolean first = true; - private boolean valid = true; + private final AtomicBoolean close = new AtomicBoolean(false); public StoreIterator(DBIterator dbIterator) { this.dbIterator = dbIterator; @@ -21,12 +22,14 @@ public StoreIterator(DBIterator dbIterator) { @Override public void close() throws IOException { - dbIterator.close(); + if (close.compareAndSet(false, true)) { + dbIterator.close(); + } } @Override public boolean hasNext() { - if (!valid) { + if (close.get()) { return false; } @@ -39,8 +42,7 @@ public boolean hasNext() { } if (!(hasNext = dbIterator.hasNext())) { // false is last item - dbIterator.close(); - valid = false; + close(); } } catch (Exception e) { logger.error(e.getMessage(), e); @@ -51,7 +53,7 @@ public boolean hasNext() { @Override public Entry next() { - if (!valid) { + if (close.get()) { throw new NoSuchElementException(); } return dbIterator.next(); @@ -61,4 +63,51 @@ public Entry next() { public void remove() { throw new UnsupportedOperationException(); } + + @Override + public void seek(byte[] key) { + checkState(); + dbIterator.seek(key); + this.first = false; + } + + @Override + public void seekToFirst() { + checkState(); + dbIterator.seekToFirst(); + this.first = false; + } + + @Override + public void seekToLast() { + checkState(); + dbIterator.seekToLast(); + this.first = false; + } + + @Override + public boolean valid() { + checkState(); + return dbIterator.hasNext(); + } + + @Override + public byte[] getKey() { + checkValid(); + return dbIterator.peekNext().getKey(); + } + + @Override + public byte[] getValue() { + checkValid(); + return dbIterator.peekNext().getValue(); + } + + @Override + public void checkState() { + if (close.get()) { + throw new IllegalStateException("iterator has been closed"); + } + } } + diff --git a/chainbase/src/main/java/org/tron/core/service/MortgageService.java b/chainbase/src/main/java/org/tron/core/service/MortgageService.java index e9b00a38201..805245d53f2 100644 --- a/chainbase/src/main/java/org/tron/core/service/MortgageService.java +++ b/chainbase/src/main/java/org/tron/core/service/MortgageService.java @@ -4,12 +4,15 @@ import java.math.BigInteger; import java.util.Comparator; import java.util.List; +import java.util.stream.Collectors; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.bouncycastle.util.encoders.Hex; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import org.tron.common.utils.Pair; import org.tron.common.utils.StringUtil; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.WitnessCapsule; @@ -18,7 +21,6 @@ import org.tron.core.store.DelegationStore; import org.tron.core.store.DynamicPropertiesStore; import org.tron.core.store.WitnessStore; -import org.tron.protos.Protocol.Vote; @Slf4j(topic = "mortgage") @Component @@ -37,6 +39,9 @@ public class MortgageService { @Setter private AccountStore accountStore; + @Autowired + private RewardViCalService rewardViCalService; + public void initStore(WitnessStore witnessStore, DelegationStore delegationStore, DynamicPropertiesStore dynamicPropertiesStore, AccountStore accountStore) { this.witnessStore = witnessStore; @@ -162,21 +167,21 @@ public long queryReward(byte[] address) { return reward + accountCapsule.getAllowance(); } - private long computeReward(long cycle, AccountCapsule accountCapsule) { + private long computeReward(long cycle, List> votes) { long reward = 0; - for (Vote vote : accountCapsule.getVotesList()) { - byte[] srAddress = vote.getVoteAddress().toByteArray(); + for (Pair vote : votes) { + byte[] srAddress = vote.getKey(); long totalReward = delegationStore.getReward(cycle, srAddress); + if (totalReward <= 0) { + continue; + } long totalVote = delegationStore.getWitnessVote(cycle, srAddress); if (totalVote == DelegationStore.REMARK || totalVote == 0) { continue; } - long userVote = vote.getVoteCount(); + long userVote = vote.getValue(); double voteRate = (double) userVote / totalVote; reward += voteRate * totalReward; - logger.debug("ComputeReward {}, {}, {}, {}, {}, {}, {}.", cycle, - Hex.toHexString(accountCapsule.getAddress().toByteArray()), Hex.toHexString(srAddress), - userVote, totalVote, totalReward, reward); } return reward; } @@ -197,23 +202,24 @@ private long computeReward(long beginCycle, long endCycle, AccountCapsule accoun long reward = 0; long newAlgorithmCycle = dynamicPropertiesStore.getNewRewardAlgorithmEffectiveCycle(); + List> srAddresses = accountCapsule.getVotesList().stream() + .map(vote -> new Pair<>(vote.getVoteAddress().toByteArray(), vote.getVoteCount())) + .collect(Collectors.toList()); if (beginCycle < newAlgorithmCycle) { long oldEndCycle = Math.min(endCycle, newAlgorithmCycle); - for (long cycle = beginCycle; cycle < oldEndCycle; cycle++) { - reward += computeReward(cycle, accountCapsule); - } + reward = getOldReward(beginCycle, oldEndCycle, srAddresses); beginCycle = oldEndCycle; } if (beginCycle < endCycle) { - for (Vote vote : accountCapsule.getVotesList()) { - byte[] srAddress = vote.getVoteAddress().toByteArray(); + for (Pair vote : srAddresses) { + byte[] srAddress = vote.getKey(); BigInteger beginVi = delegationStore.getWitnessVi(beginCycle - 1, srAddress); BigInteger endVi = delegationStore.getWitnessVi(endCycle - 1, srAddress); BigInteger deltaVi = endVi.subtract(beginVi); if (deltaVi.signum() <= 0) { continue; } - long userVote = vote.getVoteCount(); + long userVote = vote.getValue(); reward += deltaVi.multiply(BigInteger.valueOf(userVote)) .divide(DelegationStore.DECIMAL_OF_VI_REWARD).longValue(); } @@ -257,4 +263,15 @@ private void sortWitness(List list) { list.sort(Comparator.comparingLong((ByteString b) -> getWitnessByAddress(b).getVoteCount()) .reversed().thenComparing(Comparator.comparingInt(ByteString::hashCode).reversed())); } + + private long getOldReward(long begin, long end, List> votes) { + if (dynamicPropertiesStore.allowOldRewardOpt()) { + return rewardViCalService.getNewRewardAlgorithmReward(begin, end, votes); + } + long reward = 0; + for (long cycle = begin; cycle < end; cycle++) { + reward += computeReward(cycle, votes); + } + return reward; + } } diff --git a/chainbase/src/main/java/org/tron/core/service/RewardViCalService.java b/chainbase/src/main/java/org/tron/core/service/RewardViCalService.java new file mode 100644 index 00000000000..e27990f0403 --- /dev/null +++ b/chainbase/src/main/java/org/tron/core/service/RewardViCalService.java @@ -0,0 +1,286 @@ +package org.tron.core.service; + +import static org.tron.core.store.DelegationStore.DECIMAL_OF_VI_REWARD; +import static org.tron.core.store.DelegationStore.REMARK; + +import com.google.common.collect.Streams; +import com.google.common.primitives.Bytes; +import com.google.protobuf.ByteString; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import java.util.stream.LongStream; +import javax.annotation.PreDestroy; +import lombok.extern.slf4j.Slf4j; +import org.bouncycastle.util.encoders.Hex; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.tron.common.error.TronDBException; +import org.tron.common.es.ExecutorServiceManager; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.MerkleRoot; +import org.tron.common.utils.Pair; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.db.common.iterator.DBIterator; +import org.tron.core.db2.common.DB; +import org.tron.core.store.DelegationStore; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.core.store.RewardViStore; +import org.tron.core.store.WitnessStore; + +@Component +@Slf4j(topic = "rewardViCalService") +public class RewardViCalService { + + private final DB propertiesStore; + private final DB delegationStore; + private final DB witnessStore; + + @Autowired + private RewardViStore rewardViStore; + + private static final byte[] IS_DONE_KEY = new byte[]{0x00}; + private static final byte[] IS_DONE_VALUE = new byte[]{0x01}; + + private long newRewardCalStartCycle = Long.MAX_VALUE; + + private volatile long lastBlockNumber = -1; + + private static final String MAIN_NET_ROOT_HEX = + "9debcb9924055500aaae98cdee10501c5c39d4daa75800a996f4bdda73dbccd8"; + + private final Sha256Hash rewardViRoot = CommonParameter.getInstance().getStorage().getDbRoot( + "reward-vi", Sha256Hash.wrap(ByteString.fromHex(MAIN_NET_ROOT_HEX))); + + private final CountDownLatch lock = new CountDownLatch(1); + + private final ScheduledExecutorService es = ExecutorServiceManager + .newSingleThreadScheduledExecutor("rewardViCalService"); + + + @Autowired + public RewardViCalService(@Autowired DynamicPropertiesStore propertiesStore, + @Autowired DelegationStore delegationStore, @Autowired WitnessStore witnessStore) { + this.propertiesStore = propertiesStore.getDb(); + this.delegationStore = delegationStore.getDb(); + this.witnessStore = witnessStore.getDb(); + } + + public void init() { + // after init, we can get the latest block header number from db + this.newRewardCalStartCycle = this.getNewRewardAlgorithmEffectiveCycle(); + boolean ret = this.newRewardCalStartCycle != Long.MAX_VALUE; + if (ret) { + // checkpoint is flushed to db, we can start rewardViCalService immediately + lastBlockNumber = Long.MAX_VALUE; + } + es.scheduleWithFixedDelay(this::maybeRun, 0, 3, TimeUnit.SECONDS); + } + + private boolean enableNewRewardAlgorithm() { + this.newRewardCalStartCycle = this.getNewRewardAlgorithmEffectiveCycle(); + boolean ret = this.newRewardCalStartCycle != Long.MAX_VALUE; + if (ret && lastBlockNumber == -1) { + lastBlockNumber = this.getLatestBlockHeaderNumber(); + } + return ret; + } + + private boolean isDone() { + return rewardViStore.has(IS_DONE_KEY); + } + + private void maybeRun() { + try { + if (enableNewRewardAlgorithm()) { + if (this.newRewardCalStartCycle > 1) { + if (isDone()) { + this.clearUp(true); + logger.info("rewardViCalService is already done"); + } else { + if (lastBlockNumber == Long.MAX_VALUE // start rewardViCalService immediately + || this.getLatestBlockHeaderNumber() > lastBlockNumber) { + // checkpoint is flushed to db, so we can start rewardViCalService + startRewardCal(); + clearUp(true); + } else { + logger.info("startRewardCal will run after checkpoint is flushed to db"); + } + } + } else { + clearUp(false); + logger.info("rewardViCalService is no need to run"); + } + } + } catch (Exception e) { + logger.error(" Find fatal error, program will be exited soon.", e); + System.exit(1); + } + } + + private void clearUp(boolean isDone) { + lock.countDown(); + if (isDone) { + calcMerkleRoot(); + } + es.shutdown(); + } + + @PreDestroy + private void destroy() { + es.shutdownNow(); + } + + + public long getNewRewardAlgorithmReward(long beginCycle, long endCycle, + List> votes) { + if (!isDone()) { + logger.warn("rewardViCalService is not done, wait for it"); + try { + lock.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new TronDBException(e); + } + } + + long reward = 0; + if (beginCycle < endCycle) { + for (Pair vote : votes) { + byte[] srAddress = vote.getKey(); + BigInteger beginVi = getWitnessVi(beginCycle - 1, srAddress); + BigInteger endVi = getWitnessVi(endCycle - 1, srAddress); + BigInteger deltaVi = endVi.subtract(beginVi); + if (deltaVi.signum() <= 0) { + continue; + } + long userVote = vote.getValue(); + reward += deltaVi.multiply(BigInteger.valueOf(userVote)) + .divide(DelegationStore.DECIMAL_OF_VI_REWARD).longValue(); + } + } + return reward; + + } + + private void calcMerkleRoot() { + logger.info("calcMerkleRoot start"); + DBIterator iterator = rewardViStore.iterator(); + iterator.seekToFirst(); + ArrayList ids = Streams.stream(iterator) + .map(this::getHash) + .collect(Collectors.toCollection(ArrayList::new)); + + Sha256Hash rewardViRootLocal = MerkleRoot.root(ids); + if (!Objects.equals(rewardViRoot, rewardViRootLocal)) { + logger.warn("Merkle root mismatch, expect: {}, actual: {}." + + " If you are quite sure that there is no miscalculation (not on the main network)" + + ", please configure 'storage.merkleRoot.reward-vi = {}'" + + "(for a specific network such as Nile, etc.) in config.conf to fix the hints", + rewardViRoot, rewardViRootLocal, rewardViRootLocal); + } + logger.info("calcMerkleRoot: {}", rewardViRootLocal); + } + + private Sha256Hash getHash(Map.Entry entry) { + return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), + Bytes.concat(entry.getKey(), entry.getValue())); + } + + private void startRewardCal() { + logger.info("rewardViCalService start"); + rewardViStore.reset(); + DBIterator iterator = (DBIterator) witnessStore.iterator(); + iterator.seekToFirst(); + iterator.forEachRemaining(e -> accumulateWitnessReward(e.getKey())); + rewardViStore.put(IS_DONE_KEY, IS_DONE_VALUE); + logger.info("rewardViCalService is done"); + + } + + private void accumulateWitnessReward(byte[] witness) { + long startCycle = 1; + LongStream.range(startCycle, newRewardCalStartCycle) + .forEach(cycle -> accumulateWitnessVi(cycle, witness)); + } + + private void accumulateWitnessVi(long cycle, byte[] address) { + BigInteger preVi = getWitnessVi(cycle - 1, address); + long voteCount = getWitnessVote(cycle, address); + long reward = getReward(cycle, address); + if (reward == 0 || voteCount == 0) { // Just forward pre vi + if (!BigInteger.ZERO.equals(preVi)) { // Zero vi will not be record + setWitnessVi(cycle, address, preVi); + } + } else { // Accumulate delta vi + BigInteger deltaVi = BigInteger.valueOf(reward) + .multiply(DECIMAL_OF_VI_REWARD) + .divide(BigInteger.valueOf(voteCount)); + setWitnessVi(cycle, address, preVi.add(deltaVi)); + } + } + + private void setWitnessVi(long cycle, byte[] address, BigInteger value) { + byte[] k = buildViKey(cycle, address); + byte[] v = value.toByteArray(); + rewardViStore.put(k, v); + } + + private BigInteger getWitnessVi(long cycle, byte[] address) { + + byte[] v = rewardViStore.get(buildViKey(cycle, address)); + if (v == null) { + return BigInteger.ZERO; + } else { + return new BigInteger(v); + } + } + + private byte[] buildViKey(long cycle, byte[] address) { + return generateKey(cycle, address, "vi"); + } + + private long getReward(long cycle, byte[] address) { + byte[] value = this.delegationStore.get(generateKey(cycle, address, "reward")); + return value == null ? 0 : ByteArray.toLong(value); + } + + private long getWitnessVote(long cycle, byte[] address) { + byte[] value = this.delegationStore.get(generateKey(cycle, address, "vote")); + return value == null ? REMARK : ByteArray.toLong(value); + } + + private byte[] generateKey(long cycle, byte[] address, String suffix) { + return generateKey(cycle + "", address, suffix); + } + + private byte[] generateKey(String prefix, byte[] address, String suffix) { + StringBuilder sb = new StringBuilder(); + if (prefix != null) { + sb.append(prefix).append("-"); + } + sb.append(Hex.toHexString(address)); + if (suffix != null) { + sb.append("-").append(suffix); + } + return sb.toString().getBytes(); + } + + private long getNewRewardAlgorithmEffectiveCycle() { + byte[] value = this.propertiesStore.get("NEW_REWARD_ALGORITHM_EFFECTIVE_CYCLE".getBytes()); + return value == null ? Long.MAX_VALUE : ByteArray.toLong(value); + } + + private long getLatestBlockHeaderNumber() { + byte[] value = this.propertiesStore.get("latest_block_header_number".getBytes()); + return value == null ? 1 : ByteArray.toLong(value); + } +} + diff --git a/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java b/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java index f3059d31558..bf788232640 100644 --- a/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java +++ b/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java @@ -217,6 +217,8 @@ public class DynamicPropertiesStore extends TronStoreWithRevoking private static final byte[] MAX_DELEGATE_LOCK_PERIOD = "MAX_DELEGATE_LOCK_PERIOD".getBytes(); + private static final byte[] ALLOW_OLD_REWARD_OPT = "ALLOW_OLD_REWARD_OPT".getBytes(); + @Autowired private DynamicPropertiesStore(@Value("properties") String dbName) { super(dbName); @@ -2833,6 +2835,21 @@ public boolean supportMaxDelegateLockPeriod() { getUnfreezeDelayDays() > 0; } + public void saveAllowOldRewardOpt(long allowOldRewardOpt) { + this.put(ALLOW_OLD_REWARD_OPT, new BytesCapsule(ByteArray.fromLong(allowOldRewardOpt))); + } + + public boolean allowOldRewardOpt() { + return getAllowOldRewardOpt() == 1L; + } + + public long getAllowOldRewardOpt() { + return Optional.ofNullable(getUnchecked(ALLOW_OLD_REWARD_OPT)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElse(CommonParameter.getInstance().getAllowOldRewardOpt()); + } + private static class DynamicResourceProperties { private static final byte[] ONE_DAY_NET_LIMIT = "ONE_DAY_NET_LIMIT".getBytes(); diff --git a/chainbase/src/main/java/org/tron/core/store/RewardViStore.java b/chainbase/src/main/java/org/tron/core/store/RewardViStore.java new file mode 100755 index 00000000000..f173cecc00f --- /dev/null +++ b/chainbase/src/main/java/org/tron/core/store/RewardViStore.java @@ -0,0 +1,43 @@ +package org.tron.core.store; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.tron.core.db.TronDatabase; +import org.tron.core.db.common.iterator.DBIterator; + +@Slf4j(topic = "DB") +@Component +public class RewardViStore extends TronDatabase { + + @Autowired + private RewardViStore(@Value("reward-vi") String dbName) { + super(dbName); + } + + @Override + public byte[] get(byte[] key) { + return dbSource.getData(key); + } + + @Override + public void put(byte[] key, byte[] item) { + dbSource.putData(key, item); + } + + @Override + public void delete(byte[] key) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean has(byte[] key) { + return dbSource.getData(key) != null; + } + + @Override + public DBIterator iterator() { + return ((DBIterator) dbSource.iterator()); + } +} diff --git a/common/build.gradle b/common/build.gradle index 0431316c009..6c1545e5d13 100644 --- a/common/build.gradle +++ b/common/build.gradle @@ -8,7 +8,6 @@ sourceCompatibility = 1.8 // Dependency versions // --------------------------------------- - def leveldbVersion = "1.8" // -------------------------------------- @@ -30,13 +29,7 @@ if (isWindows()) { } } -repositories { - mavenCentral() -} - dependencies { - testCompile group: 'junit', name: 'junit', version: '4.13.2' - compile group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.69' compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.13.4.1' compile "com.cedarsoftware:java-util:1.8.0" compile group: 'org.apache.httpcomponents', name: 'httpasyncclient', version: '4.1.1' @@ -53,7 +46,7 @@ dependencies { compile 'org.aspectj:aspectjrt:1.8.13' compile 'org.aspectj:aspectjweaver:1.8.13' compile 'org.aspectj:aspectjtools:1.8.13' - compile group: 'io.github.tronprotocol', name: 'libp2p', version: '2.1.0',{ + compile group: 'io.github.tronprotocol', name: 'libp2p', version: '2.2.1',{ exclude group: 'io.grpc', module: 'grpc-context' exclude group: 'io.grpc', module: 'grpc-core' exclude group: 'io.grpc', module: 'grpc-netty' diff --git a/common/src/main/java/org/tron/common/parameter/CommonParameter.java b/common/src/main/java/org/tron/common/parameter/CommonParameter.java index f8f6e6c5edb..95a1eb2d0ae 100644 --- a/common/src/main/java/org/tron/common/parameter/CommonParameter.java +++ b/common/src/main/java/org/tron/common/parameter/CommonParameter.java @@ -176,7 +176,7 @@ public class CommonParameter { public int nodeListenPort; @Getter @Setter - public String nodeDiscoveryBindIp; + public String nodeLanIp; @Getter @Setter public String nodeExternalIp; @@ -255,6 +255,9 @@ public class CommonParameter { public int maxHeaderListSize; @Getter @Setter + public boolean isRpcReflectionServiceEnable; + @Getter + @Setter @Parameter(names = {"--validate-sign-thread"}, description = "Num of validate thread") public int validateSignThreadNum; @Getter @@ -651,6 +654,18 @@ public class CommonParameter { @Setter public long allowCancelAllUnfreezeV2; + @Getter + @Setter + public boolean unsolidifiedBlockCheck; + + @Getter + @Setter + public int maxUnsolidifiedBlocks; + + @Getter + @Setter + public long allowOldRewardOpt; + private static double calcMaxTimeRatio() { //return max(2.0, min(5.0, 5 * 4.0 / max(Runtime.getRuntime().availableProcessors(), 1))); return 5.0; diff --git a/common/src/main/java/org/tron/common/utils/MerkleRoot.java b/common/src/main/java/org/tron/common/utils/MerkleRoot.java new file mode 100644 index 00000000000..ccd8905b6c5 --- /dev/null +++ b/common/src/main/java/org/tron/common/utils/MerkleRoot.java @@ -0,0 +1,68 @@ +package org.tron.common.utils; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import lombok.Getter; + +public class MerkleRoot { + + private MerkleRoot() { + + } + + public static Sha256Hash root(List hashList) { + List leaves = createLeaves(hashList); + while (leaves.size() > 1) { + leaves = createParentLeaves(leaves); + } + return leaves.isEmpty() ? Sha256Hash.ZERO_HASH : leaves.get(0).hash; + } + + private static List createParentLeaves(List leaves) { + int step = 2; + int len = leaves.size(); + return IntStream.iterate(0, i -> i + step) + .limit(len) + .filter(i -> i < len) + .mapToObj(i -> { + Leaf right = i + 1 < len ? leaves.get(i + 1) : null; + return createLeaf(leaves.get(i), right); + }).collect(Collectors.toList()); + } + + private static List createLeaves(List hashList) { + int step = 2; + int len = hashList.size(); + return IntStream.iterate(0, i -> i + step) + .limit(len) + .filter(i -> i < len) + .mapToObj(i -> { + Leaf right = i + 1 < len ? createLeaf(hashList.get(i + 1)) : null; + return createLeaf(createLeaf(hashList.get(i)), right); + }).collect(Collectors.toList()); + } + + private static Leaf createLeaf(Leaf left, Leaf right) { + Leaf leaf = new Leaf(); + leaf.hash = right == null ? left.hash : computeHash(left.hash, right.hash); + return leaf; + } + + private static Leaf createLeaf(Sha256Hash hash) { + Leaf leaf = new Leaf(); + leaf.hash = hash; + return leaf; + } + + private static Sha256Hash computeHash(Sha256Hash leftHash, Sha256Hash rightHash) { + return Sha256Hash.of(true, + leftHash.getByteString().concat(rightHash.getByteString()).toByteArray()); + } + + @Getter + private static class Leaf { + + private Sha256Hash hash; + } +} diff --git a/common/src/main/java/org/tron/core/Constant.java b/common/src/main/java/org/tron/core/Constant.java index ba867793b41..2cd9ea95f15 100644 --- a/common/src/main/java/org/tron/core/Constant.java +++ b/common/src/main/java/org/tron/core/Constant.java @@ -151,6 +151,8 @@ public class Constant { public static final String NODE_RPC_MAX_HEADER_LIST_SIZE = "node.rpc.maxHeaderListSize"; + public static final String NODE_RPC_REFLECTION_SERVICE = "node.rpc.reflectionService"; + public static final String NODE_OPEN_HISTORY_QUERY_WHEN_LITEFN = "node.openHistoryQueryWhenLiteFN"; public static final String BLOCK_MAINTENANCE_TIME_INTERVAL = "block.maintenanceTimeInterval"; @@ -279,8 +281,6 @@ public class Constant { public static final String EVENT_SUBSCRIBE_CONTRACT_ADDRESS = "event.subscribe.filter.contractAddress"; public static final String EVENT_SUBSCRIBE_CONTRACT_TOPIC = "event.subscribe.filter.contractTopic"; - public static final String NODE_DISCOVERY_BIND_IP = "node.discovery.bind.ip"; - public static final String NODE_DISCOVERY_EXTERNAL_IP = "node.discovery.external.ip"; public static final String NODE_BACKUP_PRIORITY = "node.backup.priority"; @@ -371,4 +371,9 @@ public class Constant { public static final String DYNAMIC_CONFIG_CHECK_INTERVAL = "node.dynamicConfig.checkInterval"; public static final String COMMITTEE_ALLOW_TVM_SHANGHAI = "committee.allowTvmShangHai"; + + public static final String UNSOLIDIFIED_BLOCK_CHECK = "node.unsolidifiedBlockCheck"; + + public static final String MAX_UNSOLIDIFIED_BLOCKS = "node.maxUnsolidifiedBlocks"; + public static final String COMMITTEE_ALLOW_OLD_REWARD_OPT = "committee.allowOldRewardOpt"; } diff --git a/common/src/main/java/org/tron/core/config/Parameter.java b/common/src/main/java/org/tron/core/config/Parameter.java index b1a948e9fdf..247826af77a 100644 --- a/common/src/main/java/org/tron/core/config/Parameter.java +++ b/common/src/main/java/org/tron/core/config/Parameter.java @@ -22,7 +22,8 @@ public enum ForkBlockVersionEnum { VERSION_4_6(25, 1596780000000L, 80), VERSION_4_7(26, 1596780000000L, 80), VERSION_4_7_1(27, 1596780000000L, 80), - VERSION_4_7_2(28, 1596780000000L, 80); + VERSION_4_7_2(28, 1596780000000L, 80), + VERSION_4_7_4(29, 1596780000000L, 80); // if add a version, modify BLOCK_VERSION simultaneously @Getter @@ -71,7 +72,7 @@ public class ChainConstant { public static final int SINGLE_REPEAT = 1; public static final int BLOCK_FILLED_SLOTS_NUMBER = 128; public static final int MAX_FROZEN_NUMBER = 1; - public static final int BLOCK_VERSION = 28; + public static final int BLOCK_VERSION = 29; public static final long FROZEN_PERIOD = 86_400_000L; public static final long DELEGATE_PERIOD = 3 * 86_400_000L; public static final long TRX_PRECISION = 1000_000L; diff --git a/common/src/main/java/org/tron/core/config/args/Storage.java b/common/src/main/java/org/tron/core/config/args/Storage.java index 22dc239c167..9cf6eb6bab1 100644 --- a/common/src/main/java/org/tron/core/config/args/Storage.java +++ b/common/src/main/java/org/tron/core/config/args/Storage.java @@ -16,6 +16,7 @@ package org.tron.core.config.args; import com.google.common.collect.Maps; +import com.google.protobuf.ByteString; import com.typesafe.config.Config; import com.typesafe.config.ConfigObject; import java.io.File; @@ -32,6 +33,7 @@ import org.tron.common.utils.DbOptionalsUtils; import org.tron.common.utils.FileUtil; import org.tron.common.utils.Property; +import org.tron.common.utils.Sha256Hash; /** * Custom storage configurations @@ -79,6 +81,8 @@ public class Storage { private static final String CACHE_STRATEGIES = "storage.cache.strategies"; public static final String TX_CACHE_INIT_OPTIMIZATION = "storage.txCache.initOptimization"; + private static final String MERKLE_ROOT = "storage.merkleRoot"; + /** * Default values of directory */ @@ -163,6 +167,9 @@ public class Storage { @Getter private Map propertyMap; + // db root + private final Map dbRoots = Maps.newConcurrentMap(); + public static String getDbEngineFromConfig(final Config config) { return config.hasPath(DB_ENGINE_CONFIG_KEY) ? config.getString(DB_ENGINE_CONFIG_KEY) : DEFAULT_DB_ENGINE; @@ -258,6 +265,18 @@ public String getCacheStrategy(CacheType dbName) { return this.cacheStrategies.getOrDefault(dbName, CacheStrategies.getCacheStrategy(dbName)); } + public Sha256Hash getDbRoot(String dbName, Sha256Hash defaultV) { + return this.dbRoots.getOrDefault(dbName, defaultV); + } + + public void setDbRoots(Config config) { + if (config.hasPath(MERKLE_ROOT)) { + config.getConfig(MERKLE_ROOT).resolve().entrySet().forEach(c -> + this.dbRoots.put(c.getKey(), Sha256Hash.wrap( + ByteString.fromHex(c.getValue().unwrapped().toString())))); + } + } + private Property createProperty(final ConfigObject conf) { Property property = new Property(); diff --git a/config/checkstyle/checkStyle.xml b/config/checkstyle/checkStyle.xml index 16fda0fdc4f..9d09ca11bee 100644 --- a/config/checkstyle/checkStyle.xml +++ b/config/checkstyle/checkStyle.xml @@ -1,7 +1,7 @@ + "https://checkstyle.sourceforge.net/dtds/configuration_1_3.dtd"> - ``` [PM2] Spawning PM2 daemon with pm2_home=/root/.pm2 [PM2] PM2 Successfully daemonized @@ -166,25 +165,6 @@ If everything goes well, your terminal console output will look like following : (8) TYjQd4xrLZQGYMdLJqsTCuXVGapPqUp9ZX (10000 TRX) (9) THCw6hPZpFcLCWDcsZg3W77rXZ9rJQPncD (10000 TRX) - Private Keys - ================== - - (0) 2b2bddbeea87cecedcaf51eef55877b65725f709d2c0fcdfea0cb52d80acd52b - (1) f08759925316dc6344af538ebe3a619aeab836a0c254adca903cc764f87b0ee9 - (2) 1afc9f033cf9c6058db366b78a9f1b9c909b1b83397c9aed795afa05e9017511 - (3) f8f5bc70e91fc177eefea43b68c97b66536ac317a9300639e9d32a9db2f18a1f - (4) 031015272915917056c117d3cc2a03491a8f22ef450af83f6783efddf7064c59 - (5) 5eb25e2c1144f216aa99bbe2139d84bb6dedfb2c1ed72f3df6684a4c6d2cd96b - (6) f0b781da23992e6a3f536cb60917c3eb6a9c5434fcf441fcb8d7c58c01d6b70e - (7) 158f60a4379688a77d4a420e2f2a3e014ebf9ed0a1a093d7dc01ba23ebc5c970 - (8) e9342bb9108f46573804890a5301530c2834dce3703cd51ab77fba6161afec00 - (9) 2e9f0c507d2ea98dc4005a1afb1b743c629f7c145ccb55f38f75ae73cf8f605c - - HD Wallet - ================== - Mnemonic: border pulse twenty cruise grief shy need raw clean possible begin climb - Base HD Path: m/44'/60'/0'/0/{account_index} - ``` diff --git a/run.md b/run.md index 112478a4db5..c0ecbe4d91f 100644 --- a/run.md +++ b/run.md @@ -14,9 +14,9 @@ Use the [Testnet Config](https://github.com/tronprotocol/TronDeployment/blob/mas **Use the executable JAR(Recommended way):** ```bash -java -jar FullNode.jar -p your private key --witness -c your config.conf(Example:/data/java-tron/config.conf) +java -jar FullNode.jar -p --witness -c your config.conf(Example:/data/java-tron/config.conf) Example: -java -jar FullNode.jar -p 650950B193DDDDB35B6E48912DD28F7AB0E7140C1BFDEFD493348F02295BD812 --witness -c /data/java-tron/config.conf +java -jar FullNode.jar -p --witness -c /data/java-tron/config.conf ``` @@ -65,9 +65,9 @@ Then observe whether block synchronization success,If synchronization successf ```bash cd build/libs -java -jar FullNode.jar -p your private key --witness -c your config.conf (Example:/data/java-tron/config.conf) +java -jar FullNode.jar -p --witness -c your config.conf (Example:/data/java-tron/config.conf) Example: -java -jar FullNode.jar -p 650950B193DDDDB35B6E48912DD28F7AB0E7140C1BFDEFD493348F02295BD812 --witness -c /data/java-tron/config.conf +java -jar FullNode.jar -p --witness -c /data/java-tron/config.conf ``` @@ -81,7 +81,7 @@ java -jar FullNode.jar -p 650950B193DDDDB35B6E48912DD28F7AB0E7140C1BFDEFD493348F Using TaskInputs.file() with something that doesn't resolve to a File object has been deprecated and is scheduled to be removed in Gradle 5.0. Use TaskInputs.files() instead. > Task :run -20:39:22.749 INFO [o.t.c.c.a.Args] private.key = 63e62a71ed39e30bac7223097a173924aad5855959de517ff2987b0e0ec89f1a +20:39:22.749 INFO [o.t.c.c.a.Args] private.key = 63e62a71ed3... 20:39:22.816 WARN [o.t.c.c.a.Args] localwitness size must be one, get the first one 20:39:22.832 INFO [o.t.p.FullNode] Here is the help message.output-directory/ 三月 22, 2018 8:39:23 下午 org.tron.core.services.RpcApiService start diff --git a/script/checkStyle.sh b/script/checkStyle.sh deleted file mode 100644 index af3d5e7df1f..00000000000 --- a/script/checkStyle.sh +++ /dev/null @@ -1,26 +0,0 @@ -./gradlew clean build -x test > build.log 2>&1 -if [ $? != 0 ];then - echo "run ./gradlew build fail, Please check you code, Or just retry this test" - exit 1 -fi -echo "------------------------------ checkStyle check ------------------------------" -#echo $BUILDKITE_PULL_REQUEST_BASE_BRANCH -#if [[ x"$BUILDKITE_PULL_REQUEST_BASE_BRANCH" != x'develop' && x"$BUILDKITE_PULL_REQUEST_BASE_BRANCH" != x'master' ]];then -# echo "BUILDKITE_PULL_REQUEST_BASE_BRANCH isnot develop or master, SKIPED" -# exit 0 -#fi - -grep -v ":checkstyleMain\|:checkstyleTest\|:lint" build.log |grep "ant:checkstyle" > checkStyle.log 2>&1 -checkNum=`cat checkStyle.log | wc -l` -if [ ${checkNum} -gt 0 ];then - echo "please fix checkStyle problem," - echo "run [ ./gradlew clean build -x test ], and you can find checkStyle report in framework/build/reports/checkstyle/" - echo "!!!!! checkStyle Num ${checkNum} !!!!!" - cat checkStyle.log - - echo "checkStyle Failed, please fix checkStyle problem" - touch checkFailTag -else - echo "checkStyle problem zero" -fi -exit 0 diff --git a/script/codecov.sh b/script/codecov.sh deleted file mode 100644 index ba83a5a8ee2..00000000000 --- a/script/codecov.sh +++ /dev/null @@ -1,5 +0,0 @@ -bash <(curl -s https://codecov.io/bash) -t ee5ed39e-1cc4-49d1-bcf9-12bce10e5b3b -s ./common/build/reports/jacoco/test/ -s ./consensus/build/reports/jacoco/test/ -s ./chainbase/build/reports/jacoco/test/ -s ./actuator/build/reports/jacoco/test/ -s ./framework/build/reports/jacoco/test/ - -#bash <(curl -s https://codecov.io/bash) -t ee5ed39e-1cc4-49d1-bcf9-12bce10e5b3b -s ./common/build/reports/jacoco/test/jacocoTestReport.xml -s ./consensus/build/reports/jacoco/test/jacocoTestReport.xml -s ./chainbase/build/reports/jacoco/test/jacocoTestReport.xml -s ./actuator/build/reports/jacoco/test/jacocoTestReport.xml -s ./framework/build/reports/jacoco/test/jacocoTestReport.xml - -#bash <(curl -s https://codecov.io/bash) -t c2f718cbe2e84c62970a892cef614689 diff --git a/script/querySonar.sh b/script/querySonar.sh deleted file mode 100644 index 8c558634304..00000000000 --- a/script/querySonar.sh +++ /dev/null @@ -1,41 +0,0 @@ -echo "current branch is : "$BUILDKITE_BRANCH -if [ $BUILDKITE_PULL_REQUEST = "false" ]; then - SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&branch="$BUILDKITE_BRANCH - Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` - echo "current branch sonarcloud status is : "$Status - if [ $Status = null ]; then - echo "wait for check finish, 5m ....." - sleep 300 - SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&branch="$BUILDKITE_BRANCH - Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` - fi - - if [ x"$Status" = x'"OK"' ];then - echo "Sonar Check Pass" - exit 0 - else - echo "Sonar Check Failed" - echo "Please visit https://sonarcloud.io/dashboard?branch="$BUILDKITE_BRANCH"&id=java-tron for more details" - exit 1 - fi -else - echo "current PR number is : "$BUILDKITE_PULL_REQUEST - SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&pullRequest="$BUILDKITE_PULL_REQUEST - Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` - if [ $Status = null ]; then - echo "wait for check finish, 5m ....." - sleep 300 - SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&pullRequest="$BUILDKITE_PULL_REQUEST - Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` - fi - - echo "current pullRequest sonarcloud status is : "$Status - if [ x"$Status" = x'"OK"' ];then - echo "Sonar Check Pass" - exit 0 - else - echo "Sonar Check Failed" - echo "Please visit https://sonarcloud.io/dashboard?id=java-tron&pullRequest="$BUILDKITE_PULL_REQUEST" for more details" - exit 1 - fi -fi \ No newline at end of file diff --git a/script/sonar.sh b/script/sonar.sh deleted file mode 100644 index b3e2b5ccf28..00000000000 --- a/script/sonar.sh +++ /dev/null @@ -1,89 +0,0 @@ -echo "------------------------------ sonar check ------------------------------" -export SONAR_SCANNER_VERSION=4.2.0.1873 -export SONAR_SCANNER_HOME=/home/java-tron/sonar-scanner-4.1.0.1829-linux -export PATH=$SONAR_SCANNER_HOME/bin:$PATH -export SONAR_SCANNER_OPTS="-server" -#export PATH=$PATH:/home/java-tron/sonar-scanner-4.1.0.1829-linux/bin - -#BUILDKITE_BRANCH="MiraculousWang:develop" - -echo "current branch is : "$BUILDKITE_BRANCH -if [ $BUILDKITE_PULL_REQUEST = "false" ]; then - - sonar-scanner \ - -Dsonar.projectKey=java-tron \ - -Dsonar.organization=tron-zhaohong \ - -Dsonar.sources=./actuator/src,./framework/src/main,./consensus/src,./chainbase/src,./common/src,./crypto/src,./protocol/src \ - -Dsonar.java.binaries=./actuator/build/classes,./framework/build/classes,./consensus/build/classes,./chainbase/build/classes,./common/build/classes,./crypto/build/classes,./protocol/build/classes \ - -Dsonar.host.url=https://sonarcloud.io \ - -Dsonar.links.homepage=https://github.com/tronprotocol/java-tron \ - -Dsonar.links.scm=https://github.com/tronprotocol/java-tron \ - -Dsoanr.links.issue=https://github.com/tronprotocol/java-tron/issues \ - -Dsonar.branch.name=$BUILDKITE_BRANCH \ - -Dsonar.coverage.jacoco.xmlReportPaths=./common/build/reports/jacoco/test/jacocoTestReport.xml,./consensus/build/reports/jacoco/test/jacocoTestReport.xml,./chainbase/build/reports/jacoco/test/jacocoTestReport.xml,./actuator/build/reports/jacoco/test/jacocoTestReport.xml,./framework/build/reports/jacoco/test/jacocoTestReport.xml \ - -Dsonar.login=1717c3c748ec2e0ea61e501b05458de243c4abcc > /data/checkStyle/sonar.log - - sleep 100 - - - SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&branch="$BUILDKITE_BRANCH - Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` - echo "current branch sonarcloud status is : "$Status - if [ $Status = null ]; then - echo "wait for check finish, 5m ....." - sleep 300 - SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&branch="$BUILDKITE_BRANCH - Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` - fi - - if [ x"$Status" = x'"OK"' ];then - echo "Sonar Check Pass" - exit 0 - else - echo ">>>>>>>>>>>>>>>>>>>>>>>>>> Sonar Check Failed <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" - echo ">>>>>>>>>>>> Please visit https://sonarcloud.io/dashboard?branch="$BUILDKITE_BRANCH"&id=java-tron for more details <<<<<<<<<<<<<<<<<<" - touch checkFailTag - exit 0 - fi -else - echo "current PR number is : "$BUILDKITE_PULL_REQUEST - - sonar-scanner \ - -Dsonar.projectKey=java-tron \ - -Dsonar.organization=tron-zhaohong \ - -Dsonar.sources=./actuator/src,./framework/src/main,./consensus/src,./chainbase/src,./common/src,./crypto/src,./protocol/src \ - -Dsonar.java.binaries=./actuator/build/classes,./framework/build/classes,./consensus/build/classes,./chainbase/build/classes,./common/build/classes,./crypto/build/classes,./protocol/build/classes \ - -Dsonar.host.url=https://sonarcloud.io \ - -Dsonar.links.homepage=https://github.com/tronprotocol/java-tron \ - -Dsonar.links.scm=https://github.com/tronprotocol/java-tron \ - -Dsoanr.links.issue=https://github.com/tronprotocol/java-tron/issues \ - -Dsonar.pullrequest.key=$BUILDKITE_PULL_REQUEST \ - -Dsonar.pullrequest.branch=$BUILDKITE_BRANCH \ - -Dsonar.pullrequest.base=$BUILDKITE_PULL_REQUEST_BASE_BRANCH \ - -Dsonar.coverage.jacoco.xmlReportPaths=./common/build/reports/jacoco/test/jacocoTestReport.xml,./consensus/build/reports/jacoco/test/jacocoTestReport.xml,./chainbase/build/reports/jacoco/test/jacocoTestReport.xml,./actuator/build/reports/jacoco/test/jacocoTestReport.xml,./framework/build/reports/jacoco/test/jacocoTestReport.xml \ - -Dsonar.login=1717c3c748ec2e0ea61e501b05458de243c4abcc > /data/checkStyle/sonar.log - - sleep 100 - - SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&pullRequest="$BUILDKITE_PULL_REQUEST - Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` - if [ $Status = null ]; then - echo "wait for check finish, 5m ....." - sleep 300 - SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&pullRequest="$BUILDKITE_PULL_REQUEST - Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` - fi - - echo "current pullRequest sonarcloud status is : "$Status - if [ x"$Status" = x'"OK"' ];then - echo "Sonar Check Pass" - exit 0 - else - echo " -------------------------------- sonar check Failed ---------------------------------" - echo ">>>>>>>>>>>>>>> Please visit https://sonarcloud.io/dashboard?id=java-tron&pullRequest="$BUILDKITE_PULL_REQUEST" for more details <<<<<<<<<<<<<<<<<<" - echo "If this Sonar problem is not caused by your modification,Make sure you local branch is newest, And merge the newest tronprotocol/java-tron" - echo ">>>>>>>>>>>>>>>>>>>>>>>>>> Sonar Check Failed <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< " - touch checkFailTag - exit 0 - fi -fi From 3a9e6b5447a006351dccd93d51dbd6c662667d46 Mon Sep 17 00:00:00 2001 From: liukai Date: Mon, 11 Mar 2024 19:28:22 +0800 Subject: [PATCH 60/60] feat(Nile): remove CacheManagerTest --- .../org/tron/common/cache/CacheManagerTest.java | 14 -------------- 1 file changed, 14 deletions(-) delete mode 100644 framework/src/main/java/org/tron/common/cache/CacheManagerTest.java diff --git a/framework/src/main/java/org/tron/common/cache/CacheManagerTest.java b/framework/src/main/java/org/tron/common/cache/CacheManagerTest.java deleted file mode 100644 index b02b135552a..00000000000 --- a/framework/src/main/java/org/tron/common/cache/CacheManagerTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.tron.common.cache; - -import org.junit.Assert; -import org.junit.Test; - -public class CacheManagerTest { - - @Test - public void allocate() { - String strategy = String.format(CacheStrategies.PATTERNS, 1, 1, "30s", 1); - TronCache cache = CacheManager.allocate(CacheType.witnessStandby, strategy); - Assert.assertNull(cache.getIfPresent("test")); - } -}