From 93ec564b1bb97a04bec3b44a8fe065d18be1243f Mon Sep 17 00:00:00 2001 From: federico Date: Thu, 24 Sep 2026 00:34:02 +0800 Subject: [PATCH] refactor(crypto): remove unused SM2 and SM3 support Remove SM2/SM3 implementations and runtime engine selection, simplify cryptographic APIs and update their callers and tests. Reject unsupported legacy crypto.engine settings before storage or keystore initialization, with migration guidance and startup regression coverage. --- .../org/tron/core/utils/TransactionUtil.java | 10 +- .../tron/core/vm/PrecompiledContracts.java | 27 +- .../program/invoke/ProgramInvokeMockImpl.java | 6 +- .../tron/common/overlay/message/Message.java | 5 +- .../java/org/tron/common/utils/Commons.java | 7 +- .../org/tron/common/utils/LocalWitnesses.java | 6 +- .../org/tron/core/capsule/BlockCapsule.java | 11 +- .../org/tron/core/capsule/CodeCapsule.java | 3 +- .../tron/core/capsule/StorageRowCapsule.java | 4 +- .../tron/core/capsule/TransactionCapsule.java | 22 +- .../tron/core/capsule/utils/MerkleTree.java | 2 +- .../tron/core/service/RewardViCalService.java | 3 +- .../common/parameter/CommonParameter.java | 8 - .../org/tron/common/utils/MerkleRoot.java | 2 +- .../org/tron/common/utils/Sha256Hash.java | 95 +- .../org/tron/common/utils/StringUtil.java | 5 +- .../src/main/java/org/tron/core/Constant.java | 3 - .../org/tron/core/config/args/MiscConfig.java | 30 +- common/src/main/resources/reference.conf | 5 - .../config/args/ConfigParityGateTest.java | 1 - .../tron/core/config/args/MiscConfigTest.java | 59 +- .../org/tron/consensus/dpos/DposTask.java | 3 +- .../pbft/message/PbftBaseMessage.java | 2 +- .../consensus/pbft/message/PbftMessage.java | 4 +- .../org/tron/common/crypto/SignUtils.java | 42 +- .../java/org/tron/common/crypto/sm2/SM2.java | 1144 ----------------- .../org/tron/common/crypto/sm2/SM2Signer.java | 262 ---- .../java/org/tron/keystore/Credentials.java | 6 - .../main/java/org/tron/keystore/Wallet.java | 6 +- .../java/org/tron/keystore/WalletUtils.java | 4 +- docs/configuration.md | 17 +- .../tron/common/backup/message/Message.java | 2 +- .../src/main/java/org/tron/core/Wallet.java | 15 +- .../java/org/tron/core/config/args/Args.java | 7 +- .../core/config/args/WitnessInitializer.java | 12 +- .../tron/core/consensus/ConsensusService.java | 6 +- .../main/java/org/tron/core/db/Manager.java | 3 +- .../messagehandler/PbftDataSyncHandler.java | 2 +- .../core/net/service/relay/RelayService.java | 13 +- .../org/tron/core/services/RpcApiService.java | 3 +- .../org/tron/core/services/http/Util.java | 8 +- .../RpcApiServiceOnSolidity.java | 4 +- .../core/services/jsonrpc/JsonRpcApiUtil.java | 9 +- .../services/jsonrpc/types/BlockResult.java | 6 +- .../zen/ShieldedTRC20ParametersBuilder.java | 2 +- .../org/tron/program/KeystoreFactory.java | 15 +- framework/src/main/resources/config.conf | 5 - .../test/java/org/tron/common/BaseTest.java | 3 +- .../java/org/tron/common/ParameterTest.java | 3 - .../tron/common/crypto/BouncyCastleTest.java | 68 +- .../org/tron/common/crypto/SM2KeyTest.java | 285 ---- .../common/crypto/SignatureInterfaceTest.java | 39 +- .../vm/ValidateMultiSignContractTest.java | 11 +- .../org/tron/common/utils/PublicMethod.java | 33 - .../org/tron/common/utils/Sha256HashTest.java | 37 +- .../common/utils/client/WalletClient.java | 21 +- .../common/utils/client/utils/Base58.java | 10 +- .../utils/client/utils/Sha256Sm3Hash.java | 333 ----- .../utils/client/utils/TransactionUtils.java | 10 +- .../tron/core/capsule/BlockCapsuleTest.java | 2 +- .../core/capsule/utils/MerkleTreeTest.java | 10 +- .../org/tron/core/config/args/ArgsTest.java | 2 +- .../core/config/args/LocalWitnessTest.java | 4 +- .../args/WitnessInitializerKeystoreTest.java | 4 +- .../config/args/WitnessInitializerTest.java | 3 +- .../java/org/tron/core/db/BlockGenerate.java | 3 +- .../org/tron/core/db/KhaosDatabaseTest.java | 22 +- .../java/org/tron/core/db/ManagerTest.java | 2 +- .../tron/core/db/TransactionExpireTest.java | 2 +- .../org/tron/core/db2/CheckpointV2Test.java | 4 +- .../messagehandler/PbftMsgHandlerTest.java | 5 +- .../core/net/services/RelayServiceTest.java | 7 +- .../core/services/RpcApiServicesTest.java | 3 +- ...GetTransactionByIdSolidityServletTest.java | 4 +- .../core/zksnark/MerkleContainerTest.java | 12 +- .../tron/core/zksnark/SendCoinShieldTest.java | 3 +- .../core/zksnark/ShieldedReceiveTest.java | 8 +- .../org/tron/keystore/CredentialsTest.java | 10 - .../java/org/tron/keystore/CrossImplTest.java | 20 +- .../keystore/WalletAddressValidationTest.java | 31 +- .../org/tron/keystore/WalletFileTest.java | 4 +- .../org/tron/keystore/WalletPropertyTest.java | 12 +- .../tron/keystore/WalletUtilsWriteTest.java | 16 +- .../program/FullNodeCryptoEngineTest.java | 123 ++ plugins/README.md | 7 +- .../java/common/org/tron/plugins/DbRoot.java | 3 +- .../org/tron/plugins/KeystoreImport.java | 11 +- .../common/org/tron/plugins/KeystoreNew.java | 7 +- .../org/tron/plugins/KeystoreUpdate.java | 7 +- .../org/tron/plugins/utils/CryptoUitls.java | 6 - .../org/tron/plugins/utils/DBUtils.java | 3 +- .../org/tron/plugins/utils/MerkleRoot.java | 2 +- .../org/tron/plugins/utils/Sha256Hash.java | 40 +- .../org/tron/plugins/KeystoreImportTest.java | 63 +- .../org/tron/plugins/KeystoreListTest.java | 12 +- .../org/tron/plugins/KeystoreNewTest.java | 36 +- .../org/tron/plugins/KeystoreUpdateTest.java | 135 +- 97 files changed, 549 insertions(+), 2868 deletions(-) delete mode 100644 crypto/src/main/java/org/tron/common/crypto/sm2/SM2.java delete mode 100644 crypto/src/main/java/org/tron/common/crypto/sm2/SM2Signer.java delete mode 100644 framework/src/test/java/org/tron/common/crypto/SM2KeyTest.java delete mode 100644 framework/src/test/java/org/tron/common/utils/client/utils/Sha256Sm3Hash.java create mode 100644 framework/src/test/java/org/tron/program/FullNodeCryptoEngineTest.java delete mode 100644 plugins/src/main/java/common/org/tron/plugins/utils/CryptoUitls.java diff --git a/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java b/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java index 8c8a69b7dfe..efb492d14c9 100644 --- a/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java +++ b/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java @@ -38,7 +38,6 @@ import org.tron.api.GrpcAPI.TransactionExtention; import org.tron.api.GrpcAPI.TransactionSignWeight; import org.tron.api.GrpcAPI.TransactionSignWeight.Result; -import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.Sha256Hash; import org.tron.core.ChainBaseManager; import org.tron.core.capsule.AccountCapsule; @@ -118,8 +117,7 @@ private static boolean validReadableBytes(byte[] bytes, int maxLength) { } public static Sha256Hash getTransactionId(Transaction transaction) { - return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()); + return Sha256Hash.of(transaction.getRawData().toByteArray()); } @@ -210,8 +208,7 @@ public TransactionSignWeight getTransactionSignWeight(Transaction trx) { trx = truncateSignatures(trx); TransactionExtention.Builder trxExBuilder = TransactionExtention.newBuilder(); trxExBuilder.setTransaction(trx); - trxExBuilder.setTxid(ByteString.copyFrom(Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), trx.getRawData().toByteArray()))); + trxExBuilder.setTxid(ByteString.copyFrom(Sha256Hash.hash(trx.getRawData().toByteArray()))); Return.Builder retBuilder = Return.newBuilder(); retBuilder.setResult(true).setCode(response_code.SUCCESS); trxExBuilder.setResult(retBuilder); @@ -246,8 +243,7 @@ public TransactionSignWeight getTransactionSignWeight(Transaction trx) { if (trx.getSignatureCount() > 0) { List approveList = new ArrayList<>(); long currentWeight = TransactionCapsule.checkWeight(permission, trx.getSignatureList(), - Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), trx.getRawData().toByteArray()), approveList); + Sha256Hash.hash(trx.getRawData().toByteArray()), approveList); tswBuilder.addAllApprovedList(approveList); tswBuilder.setCurrentWeight(currentWeight); } diff --git a/actuator/src/main/java/org/tron/core/vm/PrecompiledContracts.java b/actuator/src/main/java/org/tron/core/vm/PrecompiledContracts.java index 3993e8ed835..19b8880731a 100644 --- a/actuator/src/main/java/org/tron/core/vm/PrecompiledContracts.java +++ b/actuator/src/main/java/org/tron/core/vm/PrecompiledContracts.java @@ -375,11 +375,9 @@ private static byte[] recoverAddrBySign(byte[] sign, byte[] hash) { } try { Rsv rsv = Rsv.fromSignature(sign); - SignatureInterface signature = SignUtils.fromComponents(rsv.getR(), rsv.getS(), rsv.getV(), - CommonParameter.getInstance().isECKeyCryptoEngine()); + SignatureInterface signature = SignUtils.fromComponents(rsv.getR(), rsv.getS(), rsv.getV()); if (signature.validateComponents()) { - out = SignUtils.signatureToAddress(hash, signature, - CommonParameter.getInstance().isECKeyCryptoEngine()); + out = SignUtils.signatureToAddress(hash, signature); } } catch (Throwable any) { logger.info("ECRecover error", any.getMessage()); @@ -541,11 +539,9 @@ public long getEnergyForData(byte[] data) { public Pair execute(byte[] data) { if (data == null) { - return Pair.of(true, Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), EMPTY_BYTE_ARRAY)); + return Pair.of(true, Sha256Hash.hash(EMPTY_BYTE_ARRAY)); } - return Pair.of(true, Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), data)); + return Pair.of(true, Sha256Hash.hash(data)); } } @@ -571,11 +567,9 @@ public Pair execute(byte[] data) { data = EMPTY_BYTE_ARRAY; } - byte[] orig = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), data); + byte[] orig = Sha256Hash.hash(data); System.arraycopy(orig, 0, target, 0, 20); - return Pair.of(true, Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), target)); + return Pair.of(true, Sha256Hash.hash(target)); } } @@ -613,11 +607,9 @@ public Pair execute(byte[] data) { int sLength = data.length < 128 ? data.length - 96 : 32; System.arraycopy(data, 96, s, 0, sLength); - SignatureInterface signature = SignUtils.fromComponents(r, s, v[31] - , CommonParameter.getInstance().isECKeyCryptoEngine()); + SignatureInterface signature = SignUtils.fromComponents(r, s, v[31]); if (validateV(v) && signature.validateComponents()) { - out = new DataWord(SignUtils.signatureToAddress(h, signature - , CommonParameter.getInstance().isECKeyCryptoEngine())); + out = new DataWord(SignUtils.signatureToAddress(h, signature)); } } catch (Throwable any) { } @@ -1060,8 +1052,7 @@ public Pair execute(byte[] rawData) { byte[] data = words[2].getData(); byte[] combine = ByteUtil.merge(address, ByteArray.fromInt(permissionId), data); - byte[] hash = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), combine); + byte[] hash = Sha256Hash.hash(combine); if (VMConfig.allowTvmSelfdestructRestriction()) { int sigArraySize = words[words[3].intValueSafe() / WORD_SIZE].intValueSafe(); diff --git a/actuator/src/main/java/org/tron/core/vm/program/invoke/ProgramInvokeMockImpl.java b/actuator/src/main/java/org/tron/core/vm/program/invoke/ProgramInvokeMockImpl.java index 567ac72931a..aaef003b0aa 100644 --- a/actuator/src/main/java/org/tron/core/vm/program/invoke/ProgramInvokeMockImpl.java +++ b/actuator/src/main/java/org/tron/core/vm/program/invoke/ProgramInvokeMockImpl.java @@ -79,8 +79,7 @@ public DataWord getBalance() { public DataWord getOriginAddress() { byte[] cowPrivKey = Hash.sha3("horse".getBytes()); - byte[] addr = SignUtils.fromPrivate(cowPrivKey - , CommonParameter.getInstance().isECKeyCryptoEngine()).getAddress(); + byte[] addr = SignUtils.fromPrivate(cowPrivKey).getAddress(); return new DataWord(addr); } @@ -89,8 +88,7 @@ public DataWord getOriginAddress() { public DataWord getCallerAddress() { byte[] cowPrivKey = Hash.sha3("monkey".getBytes()); - byte[] addr = SignUtils.fromPrivate(cowPrivKey - , CommonParameter.getInstance().isECKeyCryptoEngine()).getAddress(); + byte[] addr = SignUtils.fromPrivate(cowPrivKey).getAddress(); return new DataWord(addr); } diff --git a/chainbase/src/main/java/org/tron/common/overlay/message/Message.java b/chainbase/src/main/java/org/tron/common/overlay/message/Message.java index 84c3f695686..5da9ab0abfb 100644 --- a/chainbase/src/main/java/org/tron/common/overlay/message/Message.java +++ b/chainbase/src/main/java/org/tron/common/overlay/message/Message.java @@ -74,8 +74,7 @@ public byte[] getSendBytes() { } public Sha256Hash getMessageId() { - return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - getData()); + return Sha256Hash.of(getData()); } public byte[] getData() { @@ -110,4 +109,4 @@ public boolean equals(Object o) { return Arrays.equals(data, message.data); } -} \ No newline at end of file +} diff --git a/chainbase/src/main/java/org/tron/common/utils/Commons.java b/chainbase/src/main/java/org/tron/common/utils/Commons.java index 99c20d67f11..4ebd256fc19 100644 --- a/chainbase/src/main/java/org/tron/common/utils/Commons.java +++ b/chainbase/src/main/java/org/tron/common/utils/Commons.java @@ -5,7 +5,6 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; -import org.tron.common.parameter.CommonParameter; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.ExchangeCapsule; import org.tron.core.exception.BalanceInsufficientException; @@ -30,10 +29,8 @@ public static byte[] decode58Check(String input) { } byte[] decodeData = new byte[decodeCheck.length - 4]; System.arraycopy(decodeCheck, 0, decodeData, 0, decodeData.length); - byte[] hash0 = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - decodeData); - byte[] hash1 = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - hash0); + byte[] hash0 = Sha256Hash.hash(decodeData); + byte[] hash1 = Sha256Hash.hash(hash0); if (hash1[0] == decodeCheck[decodeData.length] && hash1[1] == decodeCheck[decodeData.length + 1] && hash1[2] == decodeCheck[decodeData.length + 2] && diff --git a/chainbase/src/main/java/org/tron/common/utils/LocalWitnesses.java b/chainbase/src/main/java/org/tron/common/utils/LocalWitnesses.java index 7179045ea7e..7d42907e254 100644 --- a/chainbase/src/main/java/org/tron/common/utils/LocalWitnesses.java +++ b/chainbase/src/main/java/org/tron/common/utils/LocalWitnesses.java @@ -47,14 +47,12 @@ public LocalWitnesses(List privateKeys) { setPrivateKeys(privateKeys); } - public void initWitnessAccountAddress(final byte[] witnessAddress, - boolean isECKeyCryptoEngine) { + public void initWitnessAccountAddress(final byte[] witnessAddress) { if (witnessAddress != null) { this.witnessAccountAddress = witnessAddress; } else if (!CollectionUtils.isEmpty(privateKeys)) { byte[] privateKey = ByteArray.fromHexString(getPrivateKey()); - final SignInterface ecKey = SignUtils.fromPrivate(privateKey, - isECKeyCryptoEngine); + final SignInterface ecKey = SignUtils.fromPrivate(privateKey); this.witnessAccountAddress = ecKey.getAddress(); } } diff --git a/chainbase/src/main/java/org/tron/core/capsule/BlockCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/BlockCapsule.java index e6cbd52e595..05316e51238 100755 --- a/chainbase/src/main/java/org/tron/core/capsule/BlockCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/BlockCapsule.java @@ -166,8 +166,7 @@ private void initTxs() { // TODO add unit test for sig2.getbytes public void sign(byte[] privateKey) { - SignInterface ecKeyEngine = SignUtils - .fromPrivate(privateKey, CommonParameter.getInstance().isECKeyCryptoEngine()); + SignInterface ecKeyEngine = SignUtils.fromPrivate(privateKey); ByteString sig = ByteString.copyFrom(ecKeyEngine.Base64toBytes(ecKeyEngine.signHash(getRawHash() .getBytes()))); @@ -179,8 +178,7 @@ public void sign(byte[] privateKey) { } private Sha256Hash getRawHash() { - return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - this.block.getBlockHeader().getRawData().toByteArray()); + return Sha256Hash.of(this.block.getBlockHeader().getRawData().toByteArray()); } public boolean validateSignature(DynamicPropertiesStore dynamicPropertiesStore, @@ -188,8 +186,7 @@ public boolean validateSignature(DynamicPropertiesStore dynamicPropertiesStore, try { byte[] sigAddress = SignUtils.signatureToAddress(getRawHash().getBytes(), TransactionCapsule.getBase64FromByteString( - block.getBlockHeader().getWitnessSignature()), - CommonParameter.getInstance().isECKeyCryptoEngine()); + block.getBlockHeader().getWitnessSignature())); byte[] witnessAccountAddress = block.getBlockHeader().getRawData().getWitnessAddress() .toByteArray(); @@ -209,7 +206,7 @@ public boolean validateSignature(DynamicPropertiesStore dynamicPropertiesStore, public BlockId getBlockId() { if (blockId.equals(Sha256Hash.ZERO_HASH)) { blockId = - new BlockId(Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), + new BlockId(Sha256Hash.of( this.block.getBlockHeader().getRawData().toByteArray()), getNum()); } return blockId; diff --git a/chainbase/src/main/java/org/tron/core/capsule/CodeCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/CodeCapsule.java index 188a2bc061c..ccd02c98840 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/CodeCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/CodeCapsule.java @@ -30,8 +30,7 @@ public CodeCapsule(byte[] code) { } public Sha256Hash getCodeHash() { - return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - this.code); + return Sha256Hash.of(this.code); } @Override diff --git a/chainbase/src/main/java/org/tron/core/capsule/StorageRowCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/StorageRowCapsule.java index 82221058ff1..c6b33c04020 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/StorageRowCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/StorageRowCapsule.java @@ -19,7 +19,6 @@ import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; -import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.Sha256Hash; @@ -56,8 +55,7 @@ private void markDirty() { } public Sha256Hash getHash() { - return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - this.rowValue); + return Sha256Hash.of(this.rowValue); } public byte[] getValue() { 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 b3f560541cf..f85158119a5 100755 --- a/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java @@ -246,8 +246,7 @@ public static long checkWeight(Permission permission, List sigs, byt "Signature size is " + sig.size()); } String base64 = TransactionCapsule.getBase64FromByteString(sig); - byte[] address = SignUtils - .signatureToAddress(hash, base64, CommonParameter.getInstance().isECKeyCryptoEngine()); + byte[] address = SignUtils.signatureToAddress(hash, base64); long weight = getWeight(permission, address); if (weight == 0) { throw new PermissionException( @@ -315,11 +314,10 @@ public static byte[] hashShieldTransaction(Transaction tx, String tokenId) Transaction transaction = tx.toBuilder().clearRawData() .setRawData(rawBuilder).build(); - byte[] mergedByte = Bytes.concat(Sha256Hash - .of(CommonParameter.getInstance().isECKeyCryptoEngine(), tokenId.getBytes()).getBytes(), + byte[] mergedByte = Bytes.concat( + Sha256Hash.of(tokenId.getBytes()).getBytes(), transaction.getRawData().toByteArray()); - return Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), mergedByte).getBytes(); + return Sha256Hash.of(mergedByte).getBytes(); } // todo mv this static function to capsule util @@ -577,18 +575,15 @@ public void createTransaction(com.google.protobuf.Message message, ContractType public Sha256Hash getMerkleHash() { byte[] transBytes = this.transaction.toByteArray(); - return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - transBytes); + return Sha256Hash.of(transBytes); } private Sha256Hash getRawHash() { - return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - this.transaction.getRawData().toByteArray()); + return Sha256Hash.of(this.transaction.getRawData().toByteArray()); } public void sign(byte[] privateKey) { - SignInterface cryptoEngine = SignUtils - .fromPrivate(privateKey, CommonParameter.getInstance().isECKeyCryptoEngine()); + SignInterface cryptoEngine = SignUtils.fromPrivate(privateKey); ByteString sig = ByteString.copyFrom(cryptoEngine.Base64toBytes(cryptoEngine .signHash(getTransactionId().getBytes()))); this.transaction = this.transaction.toBuilder().addSignature(sig).build(); @@ -609,8 +604,7 @@ public void addSign(byte[] privateKey, AccountStore accountStore) } checkPermission(permissionId, permission, contract); List approveList = new ArrayList<>(); - SignInterface cryptoEngine = SignUtils - .fromPrivate(privateKey, CommonParameter.getInstance().isECKeyCryptoEngine()); + SignInterface cryptoEngine = SignUtils.fromPrivate(privateKey); byte[] address = cryptoEngine.getAddress(); if (this.transaction.getSignatureCount() > 0) { checkWeight(permission, this.transaction.getSignatureList(), 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 cb6f299e872..45586fc2308 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 @@ -70,7 +70,7 @@ private Leaf createLeaf(Sha256Hash hash) { } private Sha256Hash computeHash(Sha256Hash leftHash, Sha256Hash rightHash) { - return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), + return Sha256Hash.of( leftHash.getByteString().concat(rightHash.getByteString()).toByteArray()); } diff --git a/chainbase/src/main/java/org/tron/core/service/RewardViCalService.java b/chainbase/src/main/java/org/tron/core/service/RewardViCalService.java index f88fd02c539..f9873da5eb7 100644 --- a/chainbase/src/main/java/org/tron/core/service/RewardViCalService.java +++ b/chainbase/src/main/java/org/tron/core/service/RewardViCalService.java @@ -191,8 +191,7 @@ private void calcMerkleRoot() { } private Sha256Hash getHash(Map.Entry entry) { - return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - Bytes.concat(entry.getKey(), entry.getValue())); + return Sha256Hash.of(Bytes.concat(entry.getKey(), entry.getValue())); } private void startRewardCal() { 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 eeb92fdbd60..fa31432d58c 100644 --- a/common/src/main/java/org/tron/common/parameter/CommonParameter.java +++ b/common/src/main/java/org/tron/common/parameter/CommonParameter.java @@ -436,10 +436,6 @@ public class CommonParameter { public EventPluginConfig eventPluginConfig; @Getter public FilterQuery eventFilter; - @Getter - @Setter - public String cryptoEngine = Constant.ECKey_ENGINE; - @Getter @Setter public boolean rpcEnable = true; @@ -669,10 +665,6 @@ public static void reset() { PARAMETER = new CommonParameter(); } - public boolean isECKeyCryptoEngine() { - return cryptoEngine.equalsIgnoreCase(Constant.ECKey_ENGINE); - } - public boolean isJsonRpcFilterEnabled() { return jsonRpcHttpFullNodeEnable || jsonRpcHttpSolidityNodeEnable; diff --git a/common/src/main/java/org/tron/common/utils/MerkleRoot.java b/common/src/main/java/org/tron/common/utils/MerkleRoot.java index ccd8905b6c5..df4ddc7a6f6 100644 --- a/common/src/main/java/org/tron/common/utils/MerkleRoot.java +++ b/common/src/main/java/org/tron/common/utils/MerkleRoot.java @@ -56,7 +56,7 @@ private static Leaf createLeaf(Sha256Hash hash) { } private static Sha256Hash computeHash(Sha256Hash leftHash, Sha256Hash rightHash) { - return Sha256Hash.of(true, + return Sha256Hash.of( leftHash.getByteString().concat(rightHash.getByteString()).toByteArray()); } diff --git a/common/src/main/java/org/tron/common/utils/Sha256Hash.java b/common/src/main/java/org/tron/common/utils/Sha256Hash.java index 68225ccba63..e7ac185249a 100644 --- a/common/src/main/java/org/tron/common/utils/Sha256Hash.java +++ b/common/src/main/java/org/tron/common/utils/Sha256Hash.java @@ -31,7 +31,6 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; -import org.bouncycastle.crypto.digests.SM3Digest; /** @@ -87,8 +86,8 @@ public static Sha256Hash wrap(ByteString rawHashByteString) { * Use {@link #of(byte[])} instead: this old name is ambiguous. */ @Deprecated - public static Sha256Hash create(boolean isSha256, byte[] contents) { - return of(isSha256, contents); + public static Sha256Hash create(byte[] contents) { + return of(contents); } /** @@ -97,8 +96,8 @@ public static Sha256Hash create(boolean isSha256, byte[] contents) { * @param contents the bytes on which the hash value is calculated * @return a new instance containing the calculated (one-time) hash */ - public static Sha256Hash of(boolean isSha256, byte[] contents) { - return wrap(hash(isSha256, contents)); + public static Sha256Hash of(byte[] contents) { + return wrap(hash(contents)); } /** @@ -110,10 +109,10 @@ public static Sha256Hash of(boolean isSha256, byte[] contents) { * @return a new instance containing the calculated (one-time) hash * @throws IOException if an error occurs while reading the file */ - public static Sha256Hash of(boolean isSha256, File file) throws IOException { + public static Sha256Hash of(File file) throws IOException { try (FileInputStream in = new FileInputStream(file)) { - return of(isSha256, ByteStreams.toByteArray(in)); + return of(ByteStreams.toByteArray(in)); } } @@ -121,8 +120,8 @@ public static Sha256Hash of(boolean isSha256, File file) throws IOException { * Use {@link #twiceOf(byte[])} instead: this old name is ambiguous. */ @Deprecated - public static Sha256Hash createDouble(boolean isSha256, byte[] contents) { - return twiceOf(isSha256, contents); + public static Sha256Hash createDouble(byte[] contents) { + return twiceOf(contents); } /** @@ -131,8 +130,8 @@ public static Sha256Hash createDouble(boolean isSha256, byte[] contents) { * @param contents the bytes on which the hash value is calculated * @return a new instance containing the calculated (two-time) hash */ - public static Sha256Hash twiceOf(boolean isSha256, byte[] contents) { - return wrap(hashTwice(isSha256, contents)); + public static Sha256Hash twiceOf(byte[] contents) { + return wrap(hashTwice(contents)); } /** @@ -149,24 +148,14 @@ public static MessageDigest newDigest() { } } - /** - * Returns a new SM3 MessageDigest instance. This is a convenience method which wraps the checked - * exception that can never occur with a RuntimeException. - * - * @return a new SM3 MessageDigest instance - */ - public static SM3Digest newSM3Digest() { - return new SM3Digest(); - } - /** * Calculates the SHA-256 hash of the given bytes. * * @param input the bytes to hash * @return the hash (in big-endian order) */ - public static byte[] hash(boolean isSha256, byte[] input) { - return hash(isSha256, input, 0, input.length); + public static byte[] hash(byte[] input) { + return hash(input, 0, input.length); } /** @@ -177,19 +166,10 @@ public static byte[] hash(boolean isSha256, byte[] input) { * @param length the number of bytes to hash * @return the hash (in big-endian order) */ - public static byte[] hash(boolean isSha256, byte[] input, int offset, int length) { - if (isSha256) { - MessageDigest digest = newDigest(); - digest.update(input, offset, length); - return digest.digest(); - } else { - SM3Digest digest = newSM3Digest(); - digest.update(input, offset, length); - byte[] eHash = new byte[digest.getDigestSize()]; - digest.doFinal(eHash, 0); - return eHash; - } - + public static byte[] hash(byte[] input, int offset, int length) { + MessageDigest digest = newDigest(); + digest.update(input, offset, length); + return digest.digest(); } /** @@ -198,8 +178,8 @@ public static byte[] hash(boolean isSha256, byte[] input, int offset, int length * @param input the bytes to hash * @return the double-hash (in big-endian order) */ - public static byte[] hashTwice(boolean isSha256, byte[] input) { - return hashTwice(isSha256, input, 0, input.length); + public static byte[] hashTwice(byte[] input) { + return hashTwice(input, 0, input.length); } /** @@ -210,43 +190,22 @@ public static byte[] hashTwice(boolean isSha256, byte[] input) { * @param length the number of bytes to hash * @return the double-hash (in big-endian order) */ - public static byte[] hashTwice(boolean isSha256, byte[] input, int offset, int length) { - if (isSha256) { - MessageDigest digest = newDigest(); - digest.update(input, offset, length); - return digest.digest(digest.digest()); - } else { - SM3Digest digest = newSM3Digest(); - digest.update(input, offset, length); - byte[] eHash = new byte[digest.getDigestSize()]; - digest.doFinal(eHash, 0); - digest.reset(); - digest.update(eHash, 0, eHash.length); - digest.doFinal(eHash, 0); - return eHash; - } - + public static byte[] hashTwice(byte[] input, int offset, int length) { + MessageDigest digest = newDigest(); + digest.update(input, offset, length); + return digest.digest(digest.digest()); } /** * Calculates the hash of hash on the given byte ranges. This is equivalent to concatenating the * two ranges and then passing the result to {@link #hashTwice(byte[])}. */ - public static byte[] hashTwice(boolean isSha256, byte[] input1, int offset1, int length1, + public static byte[] hashTwice(byte[] input1, int offset1, int length1, byte[] input2, int offset2, int length2) { - if (isSha256) { - MessageDigest digest = newDigest(); - digest.update(input1, offset1, length1); - digest.update(input2, offset2, length2); - return digest.digest(digest.digest()); - } else { - SM3Digest digest = newSM3Digest(); - digest.update(input1, offset1, length1); - digest.update(input2, offset2, length2); - byte[] eHash = new byte[digest.getDigestSize()]; - digest.doFinal(eHash, 0); - return eHash; - } + MessageDigest digest = newDigest(); + digest.update(input1, offset1, length1); + digest.update(input2, offset2, length2); + return digest.digest(digest.digest()); } private byte[] generateBlockId(long blockNum, Sha256Hash blockHash) { diff --git a/common/src/main/java/org/tron/common/utils/StringUtil.java b/common/src/main/java/org/tron/common/utils/StringUtil.java index 412a70d7f9c..d4958475394 100644 --- a/common/src/main/java/org/tron/common/utils/StringUtil.java +++ b/common/src/main/java/org/tron/common/utils/StringUtil.java @@ -16,7 +16,6 @@ package org.tron.common.utils; import com.google.protobuf.ByteString; -import org.tron.common.parameter.CommonParameter; public class StringUtil { @@ -29,8 +28,8 @@ public static String createReadableString(byte[] bytes) { } public static String encode58Check(byte[] input) { - byte[] hash0 = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), input); - byte[] hash1 = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), hash0); + byte[] hash0 = Sha256Hash.hash(input); + byte[] hash1 = Sha256Hash.hash(hash0); byte[] inputCheck = new byte[input.length + 4]; System.arraycopy(input, 0, inputCheck, 0, input.length); System.arraycopy(hash1, 0, inputCheck, input.length, 4); diff --git a/common/src/main/java/org/tron/core/Constant.java b/common/src/main/java/org/tron/core/Constant.java index 5d3f3099c91..2710787b890 100644 --- a/common/src/main/java/org/tron/core/Constant.java +++ b/common/src/main/java/org/tron/core/Constant.java @@ -58,9 +58,6 @@ public class Constant { public static final String MARKET_PAIR_PRICE_TO_ORDER = "market_pair_price_to_order"; public static final String ROCKSDB = "ROCKSDB"; - // Crypto engine - public static final String ECKey_ENGINE = "ECKey"; - // Network public static final String LOCAL_HOST = "127.0.0.1"; diff --git a/common/src/main/java/org/tron/core/config/args/MiscConfig.java b/common/src/main/java/org/tron/core/config/args/MiscConfig.java index 0c6d3631ba8..d60db84579f 100644 --- a/common/src/main/java/org/tron/core/config/args/MiscConfig.java +++ b/common/src/main/java/org/tron/core/config/args/MiscConfig.java @@ -1,6 +1,7 @@ package org.tron.core.config.args; import com.typesafe.config.Config; +import com.typesafe.config.ConfigValueType; import java.util.ArrayList; import java.util.List; import lombok.Getter; @@ -9,7 +10,7 @@ /** * Miscellaneous small config domains that don't warrant their own bean class. - * Covers: storage (partial), trx, energy, crypto, seed. + * Covers: storage (partial), trx, energy, seed, and legacy crypto validation. * *

These use manual reads because they span multiple unrelated config.conf * top-level sections and some have non-standard key naming (e.g. "enery" typo). @@ -18,15 +19,18 @@ @Getter public class MiscConfig { + private static final String LEGACY_CRYPTO_ENGINE_KEY = "crypto.engine"; + private static final String SUPPORTED_CRYPTO_ENGINE = "eckey"; + private boolean needToUpdateAsset = true; private boolean historyBalanceLookup = false; private String trxReferenceBlock = "solid"; private long trxExpirationTimeInMilliseconds = Constant.TRANSACTION_DEFAULT_EXPIRATION_TIME; private long blockNumForEnergyLimit = 4727890L; - private String cryptoEngine = Constant.ECKey_ENGINE; private List seedNodeIpList = new ArrayList<>(); public static MiscConfig fromConfig(Config config) { + validateLegacyCryptoEngine(config); MiscConfig mc = new MiscConfig(); // storage @@ -48,14 +52,28 @@ public static MiscConfig fromConfig(Config config) { mc.blockNumForEnergyLimit = config.hasPath("enery.limit.block.num") ? config.getInt("enery.limit.block.num") : 4727890L; - // crypto - mc.cryptoEngine = config.hasPath("crypto.engine") - ? config.getString("crypto.engine") : Constant.ECKey_ENGINE; - // seed node mc.seedNodeIpList = config.hasPath("seed.node.ip.list") ? config.getStringList("seed.node.ip.list") : new ArrayList<>(); return mc; } + + private static void validateLegacyCryptoEngine(Config config) { + if (!config.hasPathOrNull(LEGACY_CRYPTO_ENGINE_KEY)) { + return; + } + + if (config.getIsNull(LEGACY_CRYPTO_ENGINE_KEY) + || config.getValue(LEGACY_CRYPTO_ENGINE_KEY).valueType() != ConfigValueType.STRING + || !SUPPORTED_CRYPTO_ENGINE.equalsIgnoreCase(config.getString(LEGACY_CRYPTO_ENGINE_KEY))) { + throw new IllegalArgumentException( + "SM2/SM3 support has been removed; crypto.engine only accepts eckey. " + + "For ECKey networks, remove the setting or use eckey. " + + "For existing SM2/SM3 networks, remain on a compatible release until migration; " + + "do not reuse the chain database with ECKey/SHA-256."); + } + + logger.warn("crypto.engine is deprecated and ignored; ECKey and SHA-256 are always used"); + } } diff --git a/common/src/main/resources/reference.conf b/common/src/main/resources/reference.conf index 7c5ee1da8a6..c45707bea29 100644 --- a/common/src/main/resources/reference.conf +++ b/common/src/main/resources/reference.conf @@ -163,11 +163,6 @@ node.backup { ] } -# Algorithm for generating public key from private key. Do not modify to avoid forks. -crypto { - engine = "eckey" # Signature engine. -} - # Energy limit block number (config key has typo "enery" preserved for backward compatibility) enery.limit.block.num = 4727890 diff --git a/common/src/test/java/org/tron/core/config/args/ConfigParityGateTest.java b/common/src/test/java/org/tron/core/config/args/ConfigParityGateTest.java index cbfedb96643..c5dd29de973 100644 --- a/common/src/test/java/org/tron/core/config/args/ConfigParityGateTest.java +++ b/common/src/test/java/org/tron/core/config/args/ConfigParityGateTest.java @@ -110,7 +110,6 @@ private static final class Section { // sneaks in" hole. See everyReferenceConfTopLevelKeyIsCovered. private static final Set TOP_LEVEL_NON_BEAN = ConfigParityCheck.allowlist( - "crypto", // MiscConfig.cryptoEngine manual-read root "enery", // MiscConfig manual-read root (preserves historical typo of "energy") "localwitness", // bound by LocalWitnessConfig, not in the *ConfigBean factory pattern "net", // deprecated wrapper for net.type; intentionally empty in reference.conf diff --git a/common/src/test/java/org/tron/core/config/args/MiscConfigTest.java b/common/src/test/java/org/tron/core/config/args/MiscConfigTest.java index 89a2d6e7b3c..73f214b0920 100644 --- a/common/src/test/java/org/tron/core/config/args/MiscConfigTest.java +++ b/common/src/test/java/org/tron/core/config/args/MiscConfigTest.java @@ -2,15 +2,42 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; +import org.junit.After; +import org.junit.Before; import org.junit.Test; +import org.slf4j.LoggerFactory; import org.tron.core.Constant; public class MiscConfigTest { + private final Logger logger = (Logger) LoggerFactory.getLogger(MiscConfig.class); + private final ListAppender appender = new ListAppender<>(); + private Level originalLevel; + + @Before + public void setUp() { + originalLevel = logger.getLevel(); + logger.setLevel(Level.WARN); + appender.start(); + logger.addAppender(appender); + } + + @After + public void tearDown() { + logger.detachAppender(appender); + appender.stop(); + logger.setLevel(originalLevel); + } + private static Config withRef(String hocon) { return ConfigFactory.parseString(hocon).withFallback(ConfigFactory.defaultReference()); } @@ -28,10 +55,9 @@ public void testDefaults() { assertEquals("solid", mc.getTrxReferenceBlock()); assertEquals(Constant.TRANSACTION_DEFAULT_EXPIRATION_TIME, mc.getTrxExpirationTimeInMilliseconds()); - // reference.conf has crypto.engine = "eckey" (lowercase) - assertEquals("eckey", mc.getCryptoEngine()); // reference.conf has seed.node.ip.list with actual IPs assertFalse(mc.getSeedNodeIpList().isEmpty()); + assertTrue(appender.list.isEmpty()); } @Test @@ -40,13 +66,38 @@ public void testFromConfig() { "storage { needToUpdateAsset = false," + " balance { history { lookup = true } } }\n" + "trx { reference { block = head } }\n" - + "crypto { engine = sm2 }\n" + "seed.node { ip.list = [\"1.2.3.4:18888\"] }"); MiscConfig mc = MiscConfig.fromConfig(config); assertFalse(mc.isNeedToUpdateAsset()); assertTrue(mc.isHistoryBalanceLookup()); assertEquals("head", mc.getTrxReferenceBlock()); - assertEquals("sm2", mc.getCryptoEngine()); assertEquals(1, mc.getSeedNodeIpList().size()); } + + @Test + public void testLegacyEckeyWarning() { + for (String engine : new String[]{"eckey", "ECKey"}) { + appender.list.clear(); + MiscConfig.fromConfig(withRef("crypto.engine = " + engine)); + assertEquals(1, appender.list.size()); + assertEquals(Level.WARN, appender.list.get(0).getLevel()); + assertEquals("crypto.engine is deprecated and ignored; ECKey and SHA-256 are always used", + appender.list.get(0).getFormattedMessage()); + } + } + + @Test + public void testUnsupportedCryptoEngine() { + for (String engine : new String[]{"sm2", "SM2", "unknown", "\"\"", "null", "true", + "42", "[]", "{}"}) { + Config config = withRef("crypto.engine = " + engine); + IllegalArgumentException exception = assertThrows(engine, IllegalArgumentException.class, + () -> MiscConfig.fromConfig(config)); + assertTrue(exception.getMessage().contains("SM2/SM3 support has been removed")); + assertTrue(exception.getMessage().contains("crypto.engine only accepts eckey")); + assertTrue(exception.getMessage().contains("remain on a compatible release")); + assertTrue(exception.getMessage().contains("do not reuse the chain database")); + assertTrue(appender.list.isEmpty()); + } + } } diff --git a/consensus/src/main/java/org/tron/consensus/dpos/DposTask.java b/consensus/src/main/java/org/tron/consensus/dpos/DposTask.java index 38f5614e571..38b9ce976c9 100644 --- a/consensus/src/main/java/org/tron/consensus/dpos/DposTask.java +++ b/consensus/src/main/java/org/tron/consensus/dpos/DposTask.java @@ -125,8 +125,7 @@ private State produceBlock() { raw.getNumber(), Time.getIsoTimeString(raw.getTimestamp()), ByteArray.toHexString(raw.getWitnessAddress().toByteArray()), - new Sha256Hash(raw.getNumber(), Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), raw.toByteArray())), + new Sha256Hash(raw.getNumber(), Sha256Hash.of(raw.toByteArray())), ByteArray.toHexString(raw.getParentHash().toByteArray())); } } finally { diff --git a/consensus/src/main/java/org/tron/consensus/pbft/message/PbftBaseMessage.java b/consensus/src/main/java/org/tron/consensus/pbft/message/PbftBaseMessage.java index 4eb61f3e22e..dd8a78a28d6 100644 --- a/consensus/src/main/java/org/tron/consensus/pbft/message/PbftBaseMessage.java +++ b/consensus/src/main/java/org/tron/consensus/pbft/message/PbftBaseMessage.java @@ -95,7 +95,7 @@ public DataType getDataType() { public abstract String getNo(); public void analyzeSignature() throws SignatureException { - byte[] hash = Sha256Hash.hash(true, getPbftMessage().getRawData().toByteArray()); + byte[] hash = Sha256Hash.hash(getPbftMessage().getRawData().toByteArray()); publicKey = ECKey.signatureToAddress(hash, TransactionCapsule .getBase64FromByteString(getPbftMessage().getSignature())); } 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..dbb49bcacb5 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 @@ -62,7 +62,7 @@ private static PbftMessage buildCommon(DataType dataType, ByteString data, Block rawBuilder.setViewN(viewN).setEpoch(epoch).setDataType(dataType) .setMsgType(MsgType.PREPREPARE).setData(data); Raw raw = rawBuilder.build(); - byte[] hash = Sha256Hash.hash(true, raw.toByteArray()); + byte[] hash = Sha256Hash.hash(raw.toByteArray()); ECDSASignature signature = ecKey.sign(hash); builder.setRawData(raw).setSignature(ByteString.copyFrom(signature.toByteArray())); PBFTMessage message = builder.build(); @@ -104,7 +104,7 @@ private PbftMessage buildMessageCapsule(MsgType type, Miner miner) { .setMsgType(type).setEpoch(getPbftMessage().getRawData().getEpoch()) .setData(getPbftMessage().getRawData().getData()); Raw raw = rawBuilder.build(); - byte[] hash = Sha256Hash.hash(true, raw.toByteArray()); + byte[] hash = Sha256Hash.hash(raw.toByteArray()); ECDSASignature signature = ecKey.sign(hash); builder.setRawData(raw).setSignature(ByteString.copyFrom(signature.toByteArray())); PBFTMessage message = builder.build(); diff --git a/crypto/src/main/java/org/tron/common/crypto/SignUtils.java b/crypto/src/main/java/org/tron/common/crypto/SignUtils.java index e0e20fb2677..2fbadc70f08 100644 --- a/crypto/src/main/java/org/tron/common/crypto/SignUtils.java +++ b/crypto/src/main/java/org/tron/common/crypto/SignUtils.java @@ -5,9 +5,6 @@ import java.security.SecureRandom; import java.security.SignatureException; -import org.tron.common.crypto.ECKey.ECDSASignature; -import org.tron.common.crypto.sm2.SM2; -import org.tron.common.crypto.sm2.SM2.SM2Signature; public class SignUtils { @@ -26,48 +23,29 @@ public static boolean isValidLength(int size) { return size >= PER_SIGN_LENGTH && size <= MAX_PER_SIGN_LENGTH; } - public static SignInterface getGeneratedRandomSign( - SecureRandom secureRandom, boolean isECKeyCryptoEngine) { - if (isECKeyCryptoEngine) { - return new ECKey(secureRandom); - } - return new SM2(secureRandom); + public static SignInterface getGeneratedRandomSign(SecureRandom secureRandom) { + return new ECKey(secureRandom); } - public static SignInterface fromPrivate(byte[] privKeyBytes, boolean isECKeyCryptoEngine) { - if (isECKeyCryptoEngine) { - return ECKey.fromPrivate(privKeyBytes); - } - return SM2.fromPrivate(privKeyBytes); + public static SignInterface fromPrivate(byte[] privKeyBytes) { + return ECKey.fromPrivate(privKeyBytes); } - public static byte[] signatureToAddress( - byte[] messageHash, String signatureBase64, boolean isECKeyCryptoEngine) + public static byte[] signatureToAddress(byte[] messageHash, String signatureBase64) throws SignatureException { try { - if (isECKeyCryptoEngine) { - return ECKey.signatureToAddress(messageHash, signatureBase64); - } - return SM2.signatureToAddress(messageHash, signatureBase64); + return ECKey.signatureToAddress(messageHash, signatureBase64); } catch (Exception e) { throw new SignatureException(e); } } - public static SignatureInterface fromComponents( - byte[] r, byte[] s, byte v, boolean isECKeyCryptoEngine) { - if (isECKeyCryptoEngine) { - return ECKey.ECDSASignature.fromComponents(r, s, v); - } - return SM2.SM2Signature.fromComponents(r, s, v); + public static SignatureInterface fromComponents(byte[] r, byte[] s, byte v) { + return ECKey.ECDSASignature.fromComponents(r, s, v); } - public static byte[] signatureToAddress( - byte[] messageHash, SignatureInterface signatureInterface, boolean isECKeyCryptoEngine) + public static byte[] signatureToAddress(byte[] messageHash, SignatureInterface signatureInterface) throws SignatureException { - if (isECKeyCryptoEngine) { - return ECKey.signatureToAddress(messageHash, (ECDSASignature) signatureInterface); - } - return SM2.signatureToAddress(messageHash, (SM2Signature) signatureInterface); + return ECKey.signatureToAddress(messageHash, (ECKey.ECDSASignature) signatureInterface); } } diff --git a/crypto/src/main/java/org/tron/common/crypto/sm2/SM2.java b/crypto/src/main/java/org/tron/common/crypto/sm2/SM2.java deleted file mode 100644 index b1d349efad3..00000000000 --- a/crypto/src/main/java/org/tron/common/crypto/sm2/SM2.java +++ /dev/null @@ -1,1144 +0,0 @@ -package org.tron.common.crypto.sm2; - -import static org.tron.common.crypto.Hash.computeAddress; -import static org.tron.common.utils.BIUtil.isLessThan; -import static org.tron.common.utils.ByteUtil.bigIntegerToBytes; - -import java.io.IOException; -import java.io.Serializable; -import java.math.BigInteger; -import java.nio.charset.Charset; -import java.security.PrivateKey; -import java.security.SecureRandom; -import java.security.SignatureException; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.security.spec.InvalidKeySpecException; -import java.util.Arrays; -import java.util.Objects; -import javax.annotation.Nullable; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.ASN1Integer; -import org.bouncycastle.asn1.DLSequence; -import org.bouncycastle.asn1.x9.X9IntegerConverter; -import org.bouncycastle.crypto.AsymmetricCipherKeyPair; -import org.bouncycastle.crypto.generators.ECKeyPairGenerator; -import org.bouncycastle.crypto.params.ECDomainParameters; -import org.bouncycastle.crypto.params.ECKeyGenerationParameters; -import org.bouncycastle.crypto.params.ECPrivateKeyParameters; -import org.bouncycastle.crypto.params.ECPublicKeyParameters; -import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey; -import org.bouncycastle.jce.spec.ECParameterSpec; -import org.bouncycastle.jce.spec.ECPrivateKeySpec; -import org.bouncycastle.math.ec.ECAlgorithms; -import org.bouncycastle.math.ec.ECCurve; -import org.bouncycastle.math.ec.ECPoint; -import org.bouncycastle.util.encoders.Base64; -import org.bouncycastle.util.encoders.Hex; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.SignInterface; -import org.tron.common.crypto.SignatureInterface; -import org.tron.common.crypto.jce.ECKeyFactory; -import org.tron.common.crypto.jce.TronCastleProvider; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.ByteUtil; - -/** - * Implement Chinese Commercial Cryptographic Standard of SM2 - */ -@Slf4j(topic = "crypto") -public class SM2 implements Serializable, SignInterface { - - private static BigInteger SM2_N = new BigInteger( - "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123", 16); - private static BigInteger SM2_P = new BigInteger( - "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF", 16); - private static BigInteger SM2_A = new BigInteger( - "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC", 16); - private static BigInteger SM2_B = new BigInteger( - "28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93", 16); - private static BigInteger SM2_GX = new BigInteger( - "32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7", 16); - private static BigInteger SM2_GY = new BigInteger( - "BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0", 16); - - private static ECDomainParameters ecc_param; - private static ECParameterSpec ecc_spec; - private static ECCurve.Fp curve; - private static ECPoint ecc_point_g; - - private static final SecureRandom secureRandom; - - - static { - secureRandom = new SecureRandom(); - curve = new ECCurve.Fp(SM2_P, SM2_A, SM2_B, null, null); - ecc_point_g = curve.createPoint(SM2_GX, SM2_GY); - ecc_param = new ECDomainParameters(curve, ecc_point_g, SM2_N); - ecc_spec = new ECParameterSpec(curve, ecc_point_g, SM2_N); - } - - protected final ECPoint pub; - - private final PrivateKey privKey; - - - // Transient because it's calculated on demand. - private transient byte[] pubKeyHash; - private transient byte[] nodeId; - - - public SM2() { - this(secureRandom); - } - /** - * Generates an entirely new keypair. - * - *

BouncyCastle will be used as the Java Security Provider - */ - - - /** - * Generate a new keypair using the given Java Security Provider. - * - *

All private key operations will use the provider. - */ - public SM2(SecureRandom secureRandom) { - - ECKeyGenerationParameters ecKeyGenerationParameters = new ECKeyGenerationParameters(ecc_param, - secureRandom); - ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator(); - keyPairGenerator.init(ecKeyGenerationParameters); - AsymmetricCipherKeyPair kp = keyPairGenerator.generateKeyPair(); - ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters) kp.getPrivate(); - ECPublicKeyParameters ecpub = (ECPublicKeyParameters) kp.getPublic(); - - BigInteger privateKey = ecpriv.getD(); - this.privKey = privateKeyFromBigInteger(privateKey); - this.pub = ecpub.getQ(); - } - - public SM2(byte[] key, boolean isPrivateKey) { - if (isPrivateKey) { - BigInteger pk = new BigInteger(1, key); - this.privKey = privateKeyFromBigInteger(pk); - this.pub = ecc_param.getG().multiply(pk); - } else { - this.privKey = null; - this.pub = ecc_param.getCurve().decodePoint(key); - } - } - - - /** - * Pair a private key with a public EC point. - * - *

All private key operations will use the provider. - */ - - public SM2(@Nullable PrivateKey privKey, ECPoint pub) { - - if (privKey == null || isECPrivateKey(privKey)) { - this.privKey = privKey; - } else { - throw new IllegalArgumentException( - "Expected EC private key, given a private key object with" + - " class " - + privKey.getClass().toString() + - " and algorithm " - + privKey.getAlgorithm()); - } - - if (pub == null) { - throw new IllegalArgumentException("Public key may not be null"); - } else { - this.pub = pub; - } - } - - /** - * Pair a private key integer with a public EC point - */ - public SM2(@Nullable BigInteger priv, ECPoint pub) { - this( - privateKeyFromBigInteger(priv), - pub - ); - } - - /** - * Convert a BigInteger into a PrivateKey object - */ - private static PrivateKey privateKeyFromBigInteger(BigInteger priv) { - if (priv == null) { - return null; - } else { - try { - return ECKeyFactory - .getInstance(TronCastleProvider.getInstance()) - .generatePrivate(new ECPrivateKeySpec(priv, - ecc_spec)); - } catch (InvalidKeySpecException ex) { - throw new AssertionError("Assumed correct key spec statically"); - } - } - } - - /* Test if a generic private key is an EC private key - * - * it is not sufficient to check that privKey is a subtype of ECPrivateKey - * as the SunPKCS11 Provider will return a generic PrivateKey instance - * a fallback that covers this case is to check the key algorithm - */ - private static boolean isECPrivateKey(PrivateKey privKey) { - return privKey instanceof ECPrivateKey || privKey.getAlgorithm() - .equals("EC"); - } - - /* Convert a Java JCE ECPublicKey into a BouncyCastle ECPoint - */ - private static ECPoint extractPublicKey(final ECPublicKey ecPublicKey) { - final java.security.spec.ECPoint publicPointW = ecPublicKey.getW(); - final BigInteger xCoord = publicPointW.getAffineX(); - final BigInteger yCoord = publicPointW.getAffineY(); - - return ecc_param.getCurve().createPoint(xCoord, yCoord); - } - - - /** - * Utility for compressing an elliptic curve point. Returns the same point if it's already - * compressed. See the ECKey class docs for a discussion of point compression. - * - * @param uncompressed - - * @return - - * @deprecated per-point compression property will be removed in Bouncy Castle - */ - public static ECPoint compressPoint(ECPoint uncompressed) { - return ecc_param.getCurve().decodePoint(uncompressed.getEncoded(true)); - } - - /** - * Utility for decompressing an elliptic curve point. Returns the same point if it's already - * compressed. See the ECKey class docs for a discussion of point compression. - * - * @param compressed - - * @return - - * @deprecated per-point compression property will be removed in Bouncy Castle - */ - public static ECPoint decompressPoint(ECPoint compressed) { - return ecc_param.getCurve().decodePoint(compressed.getEncoded(false)); - } - - /** - * Creates an SM2 given the private key only. - * - * @param privKey - - * @return - - */ - public static SM2 fromPrivate(BigInteger privKey) { - return new SM2(privKey, ecc_param.getG().multiply(privKey)); - } - - /** - * Creates an SM2 given the private key only. - * - * @param privKeyBytes - - * @return - - */ - public static SM2 fromPrivate(byte[] privKeyBytes) { - if (ByteArray.isEmpty(privKeyBytes)) { - return null; - } - return fromPrivate(new BigInteger(1, privKeyBytes)); - } - - /** - * Creates an SM2 that simply trusts the caller to ensure that point is really the result of - * multiplying the generator point by the private key. This is used to speed things up when you - * know you have the right values already. The compression state of pub will be preserved. - * - * @param priv - - * @param pub - - * @return - - */ - public static SM2 fromPrivateAndPrecalculatedPublic(BigInteger priv, - ECPoint pub) { - return new SM2(priv, pub); - } - - /** - * Creates an SM2 that simply trusts the caller to ensure that point is really the result of - * multiplying the generator point by the private key. This is used to speed things up when you - * know you have the right values already. The compression state of the point will be preserved. - * - * @param priv - - * @param pub - - * @return - - */ - public static SM2 fromPrivateAndPrecalculatedPublic(byte[] priv, byte[] - pub) { - check(priv != null, "Private key must not be null"); - check(pub != null, "Public key must not be null"); - return new SM2(new BigInteger(1, priv), ecc_param.getCurve() - .decodePoint(pub)); - } - - /** - * Creates an SM2 that cannot be used for signing, only verifying signatures, from the given - * point. The compression state of pub will be preserved. - * - * @param pub - - * @return - - */ - public static SM2 fromPublicOnly(ECPoint pub) { - return new SM2((PrivateKey) null, pub); - } - - /** - * Creates an SM2 that cannot be used for signing, only verifying signatures, from the given - * encoded point. The compression state of pub will be preserved. - * - * @param pub - - * @return - - */ - public static SM2 fromPublicOnly(byte[] pub) { - return new SM2((PrivateKey) null, ecc_param.getCurve().decodePoint(pub)); - } - - /** - * Returns public key bytes from the given private key. To convert a byte array into a BigInteger, - * use new BigInteger(1, bytes); - * - * @param privKey - - * @param compressed - - * @return - - */ - public static byte[] publicKeyFromPrivate(BigInteger privKey, boolean - compressed) { - ECPoint point = ecc_param.getG().multiply(privKey); - return point.getEncoded(compressed); - } - - /** - * Compute the encoded X, Y coordinates of a public point.

This is the encoded public key - * without the leading byte. - * - * @param pubPoint a public point - * @return 64-byte X,Y point pair - */ - public static byte[] pubBytesWithoutFormat(ECPoint pubPoint) { - final byte[] pubBytes = pubPoint.getEncoded(/* uncompressed */ false); - return Arrays.copyOfRange(pubBytes, 1, pubBytes.length); - } - - /** - * Recover the public key from an encoded node id. - * - * @param nodeId a 64-byte X,Y point pair - */ - public static SM2 fromNodeId(byte[] nodeId) { - check(nodeId.length == 64, "Expected a 64 byte node id"); - byte[] pubBytes = new byte[65]; - System.arraycopy(nodeId, 0, pubBytes, 1, nodeId.length); - pubBytes[0] = 0x04; // uncompressed - return SM2.fromPublicOnly(pubBytes); - } - - public static byte[] signatureToKeyBytes(byte[] messageHash, String - signatureBase64) throws SignatureException { - byte[] signatureEncoded; - try { - signatureEncoded = Base64.decode(signatureBase64); - } catch (RuntimeException e) { - // This is what you getData back from Bouncy Castle if base64 doesn't - // decode :( - throw new SignatureException("Could not decode base64", e); - } - // Parse the signature bytes into r/s and the selector value. - if (signatureEncoded.length < 65) { - throw new SignatureException("Signature truncated, expected 65 " + - "bytes and got " + signatureEncoded.length); - } - - return signatureToKeyBytes( - messageHash, - SM2Signature.fromComponents( - Arrays.copyOfRange(signatureEncoded, 1, 33), - Arrays.copyOfRange(signatureEncoded, 33, 65), - (byte) (signatureEncoded[0] & 0xFF))); - } - - public static byte[] signatureToKeyBytes(byte[] messageHash, - SM2Signature sig) throws - SignatureException { - check(messageHash.length == 32, "messageHash argument has length " + - messageHash.length); - int header = sig.v; - // The header byte: 0x1B = first key with even y, 0x1C = first key - // with odd y, - // 0x1D = second key with even y, 0x1E = second key - // with odd y - if (header < 27 || header > 34) { - throw new SignatureException("Header byte out of range: " + header); - } - if (header >= 31) { - header -= 4; - } - int recId = header - 27; - byte[] key = recoverPubBytesFromSignature(recId, sig, - messageHash); - if (key == null) { - throw new SignatureException("Could not recover public key from " + - "signature"); - } - return key; - } - - - public byte[] hash(byte[] message) { - SM2Signer signer = this.getSM2SignerForHash(); - return signer.generateSM3Hash(message); - } - - @Override - public byte[] getPrivateKey() { - return getPrivKeyBytes(); - } - - /** - * Gets the encoded public key value. - * - * @return 65-byte encoded public key - */ - @Override - public byte[] getPubKey() { - return pub.getEncoded(/* compressed */ false); - } - - /** - * Gets the address form of the public key. - * - * @return 21-byte address - */ - @Override - public byte[] getAddress() { - if (pubKeyHash == null) { - pubKeyHash = computeAddress(this.pub); - } - return pubKeyHash; - } - - - /** - * Compute the address of the key that signed the given signature. - * - * @param messageHash 32-byte hash of message - * @param signatureBase64 Base-64 encoded signature - * @return 20-byte address - */ - public static byte[] signatureToAddress(byte[] messageHash, String - signatureBase64) throws SignatureException { - return computeAddress(signatureToKeyBytes(messageHash, - signatureBase64)); - } - - /** - * Compute the address of the key that signed the given signature. - * - * @param messageHash 32-byte hash of message - * @param sig - - * @return 20-byte address - */ - public static byte[] signatureToAddress(byte[] messageHash, - SM2Signature sig) throws - SignatureException { - return computeAddress(signatureToKeyBytes(messageHash, sig)); - } - - /** - * Compute the key that signed the given signature. - * - * @param messageHash 32-byte hash of message - * @param signatureBase64 Base-64 encoded signature - * @return ECKey - */ - public static SM2 signatureToKey(byte[] messageHash, String - signatureBase64) throws SignatureException { - final byte[] keyBytes = signatureToKeyBytes(messageHash, - signatureBase64); - return fromPublicOnly(keyBytes); - } - - /** - * Compute the key that signed the given signature. - * - * @param messageHash 32-byte hash of message - * @param sig - - * @return ECKey - */ - public static SM2 signatureToKey(byte[] messageHash, SM2Signature - sig) throws SignatureException { - final byte[] keyBytes = signatureToKeyBytes(messageHash, sig); - return fromPublicOnly(keyBytes); - } - - /** - * Takes the SM3 hash (32 bytes) of data and returns the SM2 signature which including the v - * - * @param messageHash - - * @return - - * @throws IllegalStateException if this ECKey does not have the private part. - */ - public SM2Signature sign(byte[] messageHash) { - if (messageHash.length != 32) { - throw new IllegalArgumentException("Expected 32 byte input to " + - "SM2 signature, not " + messageHash.length); - } - // No decryption of private key required. - SM2Signer signer = getSigner(); - BigInteger[] componets = signer.generateHashSignature(messageHash); - - SM2Signature sig = new SM2Signature(componets[0], componets[1]); - // Now we have to work backwards to figure out the recId needed to - // recover the signature. - int recId = -1; - byte[] thisKey = this.pub.getEncoded(/* compressed */ false); - for (int i = 0; i < 4; i++) { - byte[] k = recoverPubBytesFromSignature(i, sig, messageHash); - if (k != null && Arrays.equals(k, thisKey)) { - recId = i; - break; - } - } - if (recId == -1) { - throw new RuntimeException("Could not construct a recoverable key" + - ". This should never happen."); - } - sig.v = (byte) (recId + 27); - return sig; - } - - /** - * Signs the given hash and returns the R and S components as BigIntegers and putData them in - * SM2Signature - * - * @param input to sign - * @return SM2Signature signature that contains the R and S components - */ - public String signHash(byte[] input) { - return sign(input).toBase64(); - } - - public byte[] Base64toBytes(String signature) { - byte[] signData = Base64.decode(signature); - byte first = (byte) (signData[0] - 27); - byte[] temp = Arrays.copyOfRange(signData, 1, 65); - return ByteUtil.appendByte(temp, first); - } - - /** - * Takes the message of data and returns the SM2 signature - * - * @param message - - * @return - - * @throws IllegalStateException if this ECKey does not have the private part. - */ - public SM2Signature signMessage(byte[] message, @Nullable String userID) { - SM2Signature sig = signMsg(message, userID); - // Now we have to work backwards to figure out the recId needed to - // recover the signature. - int recId = -1; - byte[] thisKey = this.pub.getEncoded(/* compressed */ false); - - SM2Signer signer = getSigner(); - byte[] messageHash = signer.generateSM3Hash(message); - for (int i = 0; i < 4; i++) { - byte[] k = recoverPubBytesFromSignature(i, sig, messageHash); - if (k != null && Arrays.equals(k, thisKey)) { - recId = i; - break; - } - } - if (recId == -1) { - throw new RuntimeException("Could not construct a recoverable key" + - ". This should never happen."); - } - sig.v = (byte) (recId + 27); - return sig; - } - - /** - * Signs the given hash and returns the R and S components as BigIntegers and putData them in - * SM2Signature - * - * @param msg to sign - * @return SM2Signature signature that contains the R and S components - */ - public SM2Signature signMsg(byte[] msg, @Nullable String userID) { - if (null == msg) { - throw new IllegalArgumentException("Expected signature message of " + - "SM2 is null"); - } - // No decryption of private key required. - SM2Signer signer = getSigner(); - BigInteger[] componets = signer.generateSignature(msg); - return new SM2Signature(componets[0], componets[1]); - } - - private SM2Signer getSigner() { - SM2Signer signer = new SM2Signer(); - BigInteger d = getPrivKey(); - ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(d, ecc_param); - signer.init(true, privateKeyParameters); - return signer; - } - - /** - * used to generate the SM3 hash for SM2 signature generation or verification - */ - public SM2Signer getSM2SignerForHash() { - SM2Signer signer = new SM2Signer(); - ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(pub, ecc_param); - signer.init(false, publicKeyParameters); - return signer; - } - - - /** - *

Given the components of a signature and a selector value, recover and return the public key - * that generated the signature - */ - @Nullable - public static byte[] recoverPubBytesFromSignature(int recId, - SM2Signature sig, - byte[] messageHash) { - check(recId >= 0, "recId must be positive"); - check(sig.r.signum() >= 0, "r must be positive"); - check(sig.s.signum() >= 0, "s must be positive"); - check(messageHash != null, "messageHash must not be null"); - // 1.0 For j from 0 to h (h == recId here and the loop is outside - // this function) - // 1.1 Let x = r + jn - BigInteger n = ecc_param.getN(); // Curve order. - BigInteger prime = curve.getQ(); - BigInteger i = BigInteger.valueOf((long) recId / 2); - - BigInteger e = new BigInteger(1, messageHash); - BigInteger x = sig.r.subtract(e).mod(n); // r = (x + e) mod n - x = x.add(i.multiply(n)); - // 1.2. Convert the integer x to an octet string X of length mlen - // using the conversion routine - // specified in Section 2.3.7, where mlen = ⌈(log2 p)/8⌉ or - // mlen = ⌈m/8⌉. - // 1.3. Convert the octet string (16 set binary digits)||X to an - // elliptic curve point R using the - // conversion routine specified in Section 2.3.4. If this - // conversion routine outputs “invalid”, then - // do another iteration of Step 1. - // - // More concisely, what these points mean is to use X as a compressed - // public key. - ECCurve.Fp curve = (ECCurve.Fp) ecc_param.getCurve(); - // Bouncy Castle is not consistent - // about the letter it uses for the prime. - if (x.compareTo(prime) >= 0) { - // Cannot have point co-ordinates larger than this as everything - // takes place modulo Q. - return null; - } - // Compressed allKeys require you to know an extra bit of data about the - // y-coord as there are two possibilities. - // So it's encoded in the recId. - ECPoint R = decompressKey(x, (recId & 1) == 1); - // 1.4. If nR != point at infinity, then do another iteration of - // Step 1 (callers responsibility). - if (!R.multiply(n).isInfinity()) { - return null; - } - - // recover Q from the formula: s*G + (s+r)*Q = R => Q = (s+r)^(-1) (R-s*G) - BigInteger srInv = sig.s.add(sig.r).modInverse(n); - BigInteger sNeg = BigInteger.ZERO.subtract(sig.s).mod(n); - BigInteger coeff = srInv.multiply(sNeg).mod(n); - - ECPoint.Fp q = (ECPoint.Fp) ECAlgorithms.sumOfTwoMultiplies(ecc_param - .getG(), coeff, R, srInv); - return q.getEncoded(/* compressed */ false); - } - - /** - * Decompress a compressed public key (x co-ord and low-bit of y-coord). - * - * @param xBN - - * @param yBit - - * @return - - */ - - private static ECPoint decompressKey(BigInteger xBN, boolean yBit) { - X9IntegerConverter x9 = new X9IntegerConverter(); - byte[] compEnc = x9.integerToBytes(xBN, 1 + x9.getByteLength(ecc_param - .getCurve())); - compEnc[0] = (byte) (yBit ? 0x03 : 0x02); - return ecc_param.getCurve().decodePoint(compEnc); - } - - private static void check(boolean test, String message) { - if (!test) { - throw new IllegalArgumentException(message); - } - } - - /** - *

Verifies the given SM2 signature against the message bytes using the public key bytes.

- *

When using native SM2 verification, data must be 32 bytes, and no element may be - * larger than 520 bytes.

- * - * @param data Hash of the data to verify. - * @param signature signature. - * @param pub The public key bytes to use. - * @return - - */ - public static boolean verify(byte[] data, SM2Signature signature, - byte[] pub) { - SM2Signer signer = new SM2Signer(); - ECPublicKeyParameters params = new ECPublicKeyParameters(ecc_param - .getCurve().decodePoint(pub), ecc_param); - signer.init(false, params); - try { - return signer.verifyHashSignature(data, signature.r, signature.s); - } catch (NullPointerException npe) { - // Bouncy Castle contains a bug that can cause NPEs given - // specially crafted signatures. - // Those signatures are inherently invalid/attack sigs so we just - // fail them here rather than crash the thread. - logger.error("Caught NPE inside bouncy castle", npe); - return false; - } - } - - /** - * Verifies the given ASN.1 encoded SM2 signature against a hash using the public key. - * - * @param data Hash of the data to verify. - * @param signature signature. - * @param pub The public key bytes to use. - * @return - - */ - public static boolean verify(byte[] data, byte[] signature, byte[] pub) { - return verify(data, SM2Signature.decodeFromDER(signature), pub); - } - - /** - *

Verifies the given SM2 signature against the message bytes using the public key bytes. - * - * @param msg the message data to verify. - * @param signature signature. - * @param pub The public key bytes to use. - * @return - - */ - public static boolean verifyMessage(byte[] msg, SM2Signature signature, - byte[] pub, @Nullable String userID) { - SM2Signer signer = new SM2Signer(); - ECPublicKeyParameters params = new ECPublicKeyParameters(ecc_param - .getCurve().decodePoint(pub), ecc_param); - signer.init(false, params); - try { - return signer.verifySignature(msg, signature.r, signature.s, userID); - } catch (NullPointerException npe) { - // Bouncy Castle contains a bug that can cause NPEs given - // specially crafted signatures. - // Those signatures are inherently invalid/attack sigs so we just - // fail them here rather than crash the thread. - logger.error("Caught NPE inside bouncy castle", npe); - return false; - } - } - - /** - * Verifies the given ASN.1 encoded SM2 signature against a hash using the public key. - * - * @param msg the message data to verify. - * @param signature signature. - * @param pub The public key bytes to use. - * @return - - */ - public static boolean verifyMessage(byte[] msg, byte[] signature, byte[] pub, - @Nullable String userID) { - return verifyMessage(msg, SM2Signature.decodeFromDER(signature), pub, userID); - } - - - /** - * Returns true if the given pubkey is canonical, i.e. the correct length taking into account - * compression. - * - * @param pubkey - - * @return - - */ - public static boolean isPubKeyCanonical(byte[] pubkey) { - if (pubkey[0] == 0x04) { - // Uncompressed pubkey - return pubkey.length == 65; - } else if (pubkey[0] == 0x02 || pubkey[0] == 0x03) { - // Compressed pubkey - return pubkey.length == 33; - } else { - return false; - } - } - - /** - * @param recId Which possible key to recover. - * @param sig the R and S components of the signature, wrapped. - * @param messageHash Hash of the data that was signed. - * @return 20-byte address - */ - @Nullable - public static byte[] recoverAddressFromSignature(int recId, - SM2Signature sig, - byte[] messageHash) { - final byte[] pubBytes = recoverPubBytesFromSignature(recId, sig, - messageHash); - if (pubBytes == null) { - return null; - } else { - return computeAddress(pubBytes); - } - } - - /** - * @param recId Which possible key to recover. - * @param sig the R and S components of the signature, wrapped. - * @param messageHash Hash of the data that was signed. - * @return ECKey - */ - @Nullable - public static SM2 recoverFromSignature(int recId, SM2Signature sig, - byte[] messageHash) { - final byte[] pubBytes = recoverPubBytesFromSignature(recId, sig, - messageHash); - if (pubBytes == null) { - return null; - } else { - return fromPublicOnly(pubBytes); - } - } - - /** - * Returns true if this key doesn't have access to private key bytes. This may be because it was - * never given any private key bytes to begin with (a watching key). - * - * @return - - */ - public boolean isPubKeyOnly() { - return privKey == null; - } - - /** - * Returns true if this key has access to private key bytes. Does the opposite of {@link - * #isPubKeyOnly()}. - * - * @return - - */ - public boolean hasPrivKey() { - return privKey != null; - } - - - /** - * Generates the NodeID based on this key, that is the public key without first format byte - */ - public byte[] getNodeId() { - if (nodeId == null) { - nodeId = pubBytesWithoutFormat(this.pub); - } - return nodeId; - } - - - /** - * Gets the public key in the form of an elliptic curve point object from Bouncy Castle. - * - * @return - - */ - public ECPoint getPubKeyPoint() { - return pub; - } - - /** - * Gets the private key in the form of an integer field element. The public key is derived by - * performing EC point addition this number of times (i.e. point multiplying). - * - * @return - - * @throws IllegalStateException if the private key bytes are not available. - */ - public BigInteger getPrivKey() { - if (privKey == null) { - throw new ECKey.MissingPrivateKeyException(); - } else if (privKey instanceof BCECPrivateKey) { - return ((BCECPrivateKey) privKey).getD(); - } else { - throw new ECKey.MissingPrivateKeyException(); - } - } - - public String toString() { - StringBuilder b = new StringBuilder(); - b.append("pub:").append(Hex.toHexString(pub.getEncoded(false))); - return b.toString(); - } - - /** - * Produce a string rendering of the ECKey INCLUDING the private key. Unless you absolutely need - * the private key it is better for security reasons to just use toString(). - * - * @return - - */ - public String toStringWithPrivate() { - StringBuilder b = new StringBuilder(); - b.append(toString()); - if (privKey != null && privKey instanceof BCECPrivateKey) { - b.append(" priv:").append(Hex.toHexString(((BCECPrivateKey) - privKey).getD().toByteArray())); - } - return b.toString(); - } - - /** - * Verifies the given ASN.1 encoded SM2 signature against a hash using the public key. - * - * @param data Hash of the data to verify. - * @param signature signature. - * @return - - */ - public boolean verify(byte[] data, byte[] signature) { - return SM2.verify(data, signature, getPubKey()); - } - - /** - * Verifies the given R/S pair (signature) against a hash using the public key. - * - * @param sigHash - - * @param signature - - * @return - - */ - public boolean verify(byte[] sigHash, SM2Signature signature) { - return SM2.verify(sigHash, signature, getPubKey()); - } - - /** - * Returns true if this pubkey is canonical, i.e. the correct length taking into account - * compression. - * - * @return - - */ - public boolean isPubKeyCanonical() { - return isPubKeyCanonical(pub.getEncoded(/* uncompressed */ false)); - } - - /** - * Returns a 32 byte array containing the private key, or null if the key is encrypted or public - * only - * - * @return - - */ - @Nullable - public byte[] getPrivKeyBytes() { - if (privKey == null) { - return null; - } else if (privKey instanceof BCECPrivateKey) { - return bigIntegerToBytes(((BCECPrivateKey) privKey).getD(), 32); - } else { - return null; - } - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - - if (o == null || getClass() != o.getClass()) { - return false; - } - - SM2 ecKey = (SM2) o; - - if (privKey != null && !privKey.equals(ecKey.privKey)) { - return false; - } - return pub == null || pub.equals(ecKey.pub); - } - - @Override - public int hashCode() { - return Arrays.hashCode(getPubKey()); - } - - - public static class SM2Signature implements SignatureInterface { - - /** - * The two components of the signature. - */ - public final BigInteger r, s; - public byte v; - - /** - * Constructs a signature with the given components. Does NOT automatically canonicalise the - * signature. - * - * @param r - - * @param s - - */ - public SM2Signature(BigInteger r, BigInteger s) { - this.r = r; - this.s = s; - } - - public SM2Signature(byte[] r, byte[] s, byte v) { - this.r = new BigInteger(1, r); - this.s = new BigInteger(1, s); - this.v = v; - } - - /** - * t - * - * @return - - */ - private static SM2Signature fromComponents(byte[] r, byte[] s) { - return new SM2Signature(new BigInteger(1, r), new BigInteger(1, - s)); - } - - /** - * @param r - - * @param s - - * @param v - - * @return - - */ - public static SM2Signature fromComponents(byte[] r, byte[] s, byte - v) { - SM2Signature signature = fromComponents(r, s); - signature.v = v; - return signature; - } - - public static boolean validateComponents(BigInteger r, BigInteger s, - byte v) { - - if (v != 27 && v != 28) { - return false; - } - - if (isLessThan(r, BigInteger.ONE)) { - return false; - } - if (isLessThan(s, BigInteger.ONE)) { - return false; - } - - if (!isLessThan(r, SM2.SM2_N)) { - return false; - } - return isLessThan(s, SM2.SM2_N); - } - - public static SM2Signature decodeFromDER(byte[] bytes) { - ASN1InputStream decoder = null; - try { - decoder = new ASN1InputStream(bytes); - DLSequence seq = (DLSequence) decoder.readObject(); - if (seq == null) { - throw new RuntimeException("Reached past end of ASN.1 " - + "stream."); - } - ASN1Integer r, s; - try { - r = (ASN1Integer) seq.getObjectAt(0); - s = (ASN1Integer) seq.getObjectAt(1); - } catch (ClassCastException e) { - throw new IllegalArgumentException(e); - } - // OpenSSL deviates from the DER spec by interpreting these - // values as unsigned, though they should not be - // Thus, we always use the positive versions. See: - // http://r6.ca/blog/20111119T211504Z.html - return new SM2Signature(r.getPositiveValue(), s - .getPositiveValue()); - } catch (IOException e) { - throw new RuntimeException(e); - } finally { - if (decoder != null) { - try { - decoder.close(); - } catch (IOException x) { - - } - } - } - } - - public boolean validateComponents() { - return validateComponents(r, s, v); - } - - - /** - * @return - - */ - public String toBase64() { - byte[] sigData = new byte[65]; // 1 header + 32 bytes for R + 32 - // bytes for S - sigData[0] = v; - System.arraycopy(bigIntegerToBytes(this.r, 32), 0, sigData, 1, 32); - System.arraycopy(bigIntegerToBytes(this.s, 32), 0, sigData, 33, 32); - return new String(Base64.encode(sigData), Charset.forName("UTF-8")); - } - - - public byte[] toByteArray() { - final byte fixedV = this.v >= 27 - ? (byte) (this.v - 27) - : this.v; - - return ByteUtil.merge( - ByteUtil.bigIntegerToBytes(this.r, 32), - ByteUtil.bigIntegerToBytes(this.s, 32), - new byte[]{fixedV}); - } - - public String toHex() { - return Hex.toHexString(toByteArray()); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - SM2Signature signature = (SM2Signature) o; - - if (!r.equals(signature.r)) { - return false; - } - return s.equals(signature.s); - } - - @Override - public int hashCode() { - int result = r.hashCode(); - result = 31 * result + s.hashCode(); - return result; - } - } - -} diff --git a/crypto/src/main/java/org/tron/common/crypto/sm2/SM2Signer.java b/crypto/src/main/java/org/tron/common/crypto/sm2/SM2Signer.java deleted file mode 100644 index 817b909de58..00000000000 --- a/crypto/src/main/java/org/tron/common/crypto/sm2/SM2Signer.java +++ /dev/null @@ -1,262 +0,0 @@ -package org.tron.common.crypto.sm2; - -import java.math.BigInteger; -import java.security.SecureRandom; -import javax.annotation.Nullable; -import org.bouncycastle.crypto.CipherParameters; -import org.bouncycastle.crypto.Digest; -import org.bouncycastle.crypto.digests.SM3Digest; -import org.bouncycastle.crypto.params.ECDomainParameters; -import org.bouncycastle.crypto.params.ECKeyParameters; -import org.bouncycastle.crypto.params.ECPrivateKeyParameters; -import org.bouncycastle.crypto.params.ECPublicKeyParameters; -import org.bouncycastle.crypto.params.ParametersWithID; -import org.bouncycastle.crypto.params.ParametersWithRandom; -import org.bouncycastle.crypto.signers.DSAKCalculator; -import org.bouncycastle.crypto.signers.RandomDSAKCalculator; -import org.bouncycastle.math.ec.ECConstants; -import org.bouncycastle.math.ec.ECFieldElement; -import org.bouncycastle.math.ec.ECMultiplier; -import org.bouncycastle.math.ec.ECPoint; -import org.bouncycastle.math.ec.FixedPointCombMultiplier; -import org.bouncycastle.util.BigIntegers; - -public class SM2Signer - implements ECConstants { - - private final DSAKCalculator kCalculator = new RandomDSAKCalculator(); - - private byte[] userID; - - private int curveLength; - private ECDomainParameters ecParams; - private ECPoint pubPoint; - private ECKeyParameters ecKey; - - private SecureRandom random; - - public void init(boolean forSigning, CipherParameters param) { - CipherParameters baseParam; - - if (param instanceof ParametersWithID) { - baseParam = ((ParametersWithID) param).getParameters(); - userID = ((ParametersWithID) param).getID(); - } else { - baseParam = param; - userID = new byte[0]; - } - - if (forSigning) { - if (baseParam instanceof ParametersWithRandom) { - ParametersWithRandom rParam = (ParametersWithRandom) baseParam; - - ecKey = (ECKeyParameters) rParam.getParameters(); - ecParams = ecKey.getParameters(); - kCalculator.init(ecParams.getN(), rParam.getRandom()); - } else { - ecKey = (ECKeyParameters) baseParam; - ecParams = ecKey.getParameters(); - kCalculator.init(ecParams.getN(), new SecureRandom()); - } - pubPoint = ecParams.getG().multiply(((ECPrivateKeyParameters) ecKey).getD()).normalize(); - } else { - ecKey = (ECKeyParameters) baseParam; - ecParams = ecKey.getParameters(); - pubPoint = ((ECPublicKeyParameters) ecKey).getQ(); - } - - curveLength = (ecParams.getCurve().getFieldSize() + 7) / 8; - } - - - /** - * generate the signature for the message - * - * @param message plaintext - */ - public BigInteger[] generateSignature(byte[] message) { - byte[] eHash = generateSM3Hash(message); - return generateHashSignature(eHash); - } - - /** - * generate the signature for the message - */ - - public byte[] generateSM3Hash(byte[] message) { - //byte[] msg = message.getBytes(); - - SM3Digest digest = new SM3Digest(); - byte[] z = getZ(digest); - - digest.update(z, 0, z.length); - digest.update(message, 0, message.length); - - byte[] eHash = new byte[digest.getDigestSize()]; - - digest.doFinal(eHash, 0); - return eHash; - } - - /** - * generate the signature from the 32 byte hash - */ - public BigInteger[] generateHashSignature(byte[] hash) { - if (hash.length != 32) { - throw new IllegalArgumentException("Expected 32 byte input to " + - "ECDSA signature, not " + hash.length); - } - BigInteger n = ecParams.getN(); - BigInteger e = calculateE(hash); - BigInteger d = ((ECPrivateKeyParameters) ecKey).getD(); - - BigInteger r, s; - - ECMultiplier basePointMultiplier = createBasePointMultiplier(); - - // 5.2.1 Draft RFC: SM2 Public Key Algorithms - do // generate s - { - BigInteger k; - do // generate r - { - // A3 - k = kCalculator.nextK(); - // A4 - ECPoint p = basePointMultiplier.multiply(ecParams.getG(), k).normalize(); - - // A5 - r = e.add(p.getAffineXCoord().toBigInteger()).mod(n); - } - while (r.equals(ZERO) || r.add(k).equals(n)); - - // A6 - BigInteger dPlus1ModN = d.add(ONE).modInverse(n); - - s = k.subtract(r.multiply(d)).mod(n); - s = dPlus1ModN.multiply(s).mod(n); - } - while (s.equals(ZERO)); - - // A7 - return new BigInteger[]{r, s}; - } - - /** - * verify the message signature - */ - public boolean verifySignature(byte[] message, BigInteger r, BigInteger s, - @Nullable String userID) { - BigInteger n = ecParams.getN(); - - // 5.3.1 Draft RFC: SM2 Public Key Algorithms - // B1 - if (r.compareTo(ONE) < 0 || r.compareTo(n) >= 0) { - return false; - } - - // B2 - if (s.compareTo(ONE) < 0 || s.compareTo(n) >= 0) { - return false; - } - - ECPoint q = ((ECPublicKeyParameters) ecKey).getQ(); - - if (userID != null) { - this.userID = userID.getBytes(); - } - byte[] eHash = generateSM3Hash(message); - - // B4 - BigInteger e = calculateE(eHash); - - // B5 - BigInteger t = r.add(s).mod(n); - if (t.equals(ZERO)) { - return false; - } else { - // B6 - ECPoint x1y1 = ecParams.getG().multiply(s); - x1y1 = x1y1.add(q.multiply(t)).normalize(); - - // B7 - return r.equals(e.add(x1y1.getAffineXCoord().toBigInteger()).mod(n)); - } - } - - /** - * verify the hash signature - */ - public boolean verifyHashSignature(byte[] hash, BigInteger r, BigInteger s) { - BigInteger n = ecParams.getN(); - - // 5.3.1 Draft RFC: SM2 Public Key Algorithms - // B1 - if (r.compareTo(ONE) < 0 || r.compareTo(n) >= 0) { - return false; - } - - // B2 - if (s.compareTo(ONE) < 0 || s.compareTo(n) >= 0) { - return false; - } - - ECPoint q = ((ECPublicKeyParameters) ecKey).getQ(); - - // B4 - BigInteger e = calculateE(hash); - - // B5 - BigInteger t = r.add(s).mod(n); - if (t.equals(ZERO)) { - return false; - } else { - // B6 - ECPoint x1y1 = ecParams.getG().multiply(s); - x1y1 = x1y1.add(q.multiply(t)).normalize(); - - // B7 - return r.equals(e.add(x1y1.getAffineXCoord().toBigInteger()).mod(n)); - } - } - - private byte[] getZ(Digest digest) { - - //addUserID(digest, userID); - - addFieldElement(digest, ecParams.getCurve().getA()); - addFieldElement(digest, ecParams.getCurve().getB()); - addFieldElement(digest, ecParams.getG().getAffineXCoord()); - addFieldElement(digest, ecParams.getG().getAffineYCoord()); - addFieldElement(digest, pubPoint.getAffineXCoord()); - addFieldElement(digest, pubPoint.getAffineYCoord()); - - byte[] rv = new byte[digest.getDigestSize()]; - - digest.doFinal(rv, 0); - - return rv; - } - - private void addUserID(Digest digest, byte[] userID) { - int len = userID.length * 8; - digest.update((byte) (len >> 8 & 0xFF)); - digest.update((byte) (len & 0xFF)); - digest.update(userID, 0, userID.length); - } - - private void addFieldElement(Digest digest, ECFieldElement v) { - byte[] p = BigIntegers.asUnsignedByteArray(curveLength, v.toBigInteger()); - digest.update(p, 0, p.length); - } - - protected ECMultiplier createBasePointMultiplier() { - return new FixedPointCombMultiplier(); - } - - protected BigInteger calculateE(byte[] message) { - return new BigInteger(1, message); - } - -} - diff --git a/crypto/src/main/java/org/tron/keystore/Credentials.java b/crypto/src/main/java/org/tron/keystore/Credentials.java index 1c44b21a80c..be6e6ce48c6 100644 --- a/crypto/src/main/java/org/tron/keystore/Credentials.java +++ b/crypto/src/main/java/org/tron/keystore/Credentials.java @@ -2,7 +2,6 @@ import java.util.Objects; import org.tron.common.crypto.SignInterface; -import org.tron.common.crypto.sm2.SM2; import org.tron.common.utils.StringUtil; /** @@ -23,11 +22,6 @@ public static Credentials create(SignInterface cryptoEngine) { return new Credentials(cryptoEngine, address); } - public static Credentials create(SM2 sm2Pair) { - String address = StringUtil.encode58Check(sm2Pair.getAddress()); - return new Credentials(sm2Pair, address); - } - public SignInterface getSignInterface() { return cryptoEngine; } diff --git a/crypto/src/main/java/org/tron/keystore/Wallet.java b/crypto/src/main/java/org/tron/keystore/Wallet.java index d63525b1e4d..a1f74c7891b 100644 --- a/crypto/src/main/java/org/tron/keystore/Wallet.java +++ b/crypto/src/main/java/org/tron/keystore/Wallet.java @@ -172,8 +172,8 @@ private static byte[] generateMac(byte[] derivedKey, byte[] cipherText) { return Hash.sha3(result); } - public static SignInterface decrypt(String password, WalletFile walletFile, - boolean ecKey) throws CipherException { + public static SignInterface decrypt(String password, WalletFile walletFile) + throws CipherException { validate(walletFile); @@ -216,7 +216,7 @@ public static SignInterface decrypt(String password, WalletFile walletFile, byte[] encryptKey = Arrays.copyOfRange(derivedKey, 0, 16); byte[] privateKey = performCipherOperation(Cipher.DECRYPT_MODE, iv, encryptKey, cipherText); - SignInterface keyPair = SignUtils.fromPrivate(privateKey, ecKey); + SignInterface keyPair = SignUtils.fromPrivate(privateKey); // Enforce address consistency: if the keystore declares an address, it MUST match // the address derived from the decrypted private key. Prevents address spoofing diff --git a/crypto/src/main/java/org/tron/keystore/WalletUtils.java b/crypto/src/main/java/org/tron/keystore/WalletUtils.java index 2ce100823d9..632ba9a75eb 100644 --- a/crypto/src/main/java/org/tron/keystore/WalletUtils.java +++ b/crypto/src/main/java/org/tron/keystore/WalletUtils.java @@ -119,11 +119,11 @@ public static void writeWalletFile(WalletFile walletFile, File destination) } } - public static Credentials loadCredentials(String password, File source, boolean ecKey) + public static Credentials loadCredentials(String password, File source) throws IOException, CipherException { warnIfSymbolicLink(source); WalletFile walletFile = objectMapper.readValue(source, WalletFile.class); - return Credentials.create(Wallet.decrypt(password, walletFile, ecKey)); + return Credentials.create(Wallet.decrypt(password, walletFile)); } /** diff --git a/docs/configuration.md b/docs/configuration.md index d021326a15e..a9db0ddc425 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -38,6 +38,22 @@ java-tron-1.0.0/bin/FullNode -c /path/to/node.conf -w If `-c` is omitted, the node loads the `config.conf` bundled inside the jar (the same file shipped with the distribution) merged with `reference.conf` as fallback. The bundled file already enables discovery/persist for mainnet operation. For production, copy it out, edit, and pass the edited copy via `-c` to make your configuration visible to operators. +## Migrating legacy `crypto.engine` settings + +SM2/SM3 support has been removed. The node always uses ECKey/secp256k1 and SHA-256; +`crypto.engine` no longer selects a runtime cryptographic engine. + +| Existing setting | Startup behavior | Operator action | +|------------------|------------------|-----------------| +| Key absent | Uses ECKey and SHA-256 | No change needed | +| `crypto.engine = "eckey"` (case-insensitive) | Starts with a deprecation warning | Remove the redundant setting | +| Any other value, including `"sm2"`, an empty string, `null`, or a non-string value | Fails before database or keystore initialization | Verify the network's cryptographic suite before upgrading | + +An existing SM2/SM3 deployment must remain on a compatible release until it has a +separately planned migration. Removing the setting or changing it to `eckey` does +not convert its chain data, addresses, keys, or signatures. Do not open an existing +SM2/SM3 chain database with this ECKey/SHA-256-only node. + ## Minimal Config File Your config file only needs to contain what you want to change. The following is sufficient for a mainnet full node: @@ -233,7 +249,6 @@ Not all parameters support hot-reload. Parameters that affect node identity, gen | Parameter | Reason | |-----------|--------| -| `crypto.engine` | Changing the key-derivation algorithm will fork the node | | `genesis.block.*` | Must be identical on every node in the network | | `committee.*` | Controlled by on-chain governance proposals; manual overrides are for private chains only | | `node.p2p.version` | Must match the network (11111 for mainnet) | diff --git a/framework/src/main/java/org/tron/common/backup/message/Message.java b/framework/src/main/java/org/tron/common/backup/message/Message.java index cd1a2669427..8b624637952 100644 --- a/framework/src/main/java/org/tron/common/backup/message/Message.java +++ b/framework/src/main/java/org/tron/common/backup/message/Message.java @@ -49,7 +49,7 @@ public byte[] getSendData() { } public Sha256Hash getMessageId() { - return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), getData()); + return Sha256Hash.of(getData()); } public abstract Node getFrom(); diff --git a/framework/src/main/java/org/tron/core/Wallet.java b/framework/src/main/java/org/tron/core/Wallet.java index ac54cb2b7ff..d473ed03f74 100755 --- a/framework/src/main/java/org/tron/core/Wallet.java +++ b/framework/src/main/java/org/tron/core/Wallet.java @@ -300,8 +300,7 @@ public class Wallet { * Creates a new Wallet with a random ECKey. */ public Wallet() { - this.cryptoEngine = SignUtils.getGeneratedRandomSign(Utils.getRandom(), - CommonParameter.getInstance().isECKeyCryptoEngine()); + this.cryptoEngine = SignUtils.getGeneratedRandomSign(Utils.getRandom()); } /** @@ -644,8 +643,7 @@ public TransactionApprovedList getTransactionApprovedList(Transaction trx) { trx = TransactionUtil.truncateSignatures(trx); TransactionExtention.Builder trxExBuilder = TransactionExtention.newBuilder(); trxExBuilder.setTransaction(trx); - trxExBuilder.setTxid(ByteString.copyFrom(Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), trx.getRawData().toByteArray()))); + trxExBuilder.setTxid(ByteString.copyFrom(Sha256Hash.hash(trx.getRawData().toByteArray()))); Return.Builder retBuilder = Return.newBuilder(); retBuilder.setResult(true).setCode(response_code.SUCCESS); trxExBuilder.setResult(retBuilder); @@ -679,8 +677,7 @@ public TransactionApprovedList getTransactionApprovedList(Transaction trx) { if (trx.getSignatureCount() > 0) { List approveList = new ArrayList<>(); - byte[] hash = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), trx.getRawData().toByteArray()); + byte[] hash = Sha256Hash.hash(trx.getRawData().toByteArray()); TransactionCapsule.checkWeight(permission, trx.getSignatureList(), hash, approveList); tswBuilder.addAllApprovedList(approveList); } @@ -4527,8 +4524,7 @@ public String getCoinbase() { List localWitnessAddresses = new ArrayList<>(); for (String privateKey : localPrivateKeys) { localWitnessAddresses.add(Hex.toHexString(SignUtils - .fromPrivate(ByteArray.fromHexString(privateKey), - CommonParameter.getInstance().isECKeyCryptoEngine()).getAddress())); + .fromPrivate(ByteArray.fromHexString(privateKey)).getAddress())); } // get all witnesses @@ -4558,8 +4554,7 @@ public boolean isMining() { List localWitnessAddresses = new ArrayList<>(); for (String privateKey : localPrivateKeys) { localWitnessAddresses.add(Hex.toHexString(SignUtils - .fromPrivate(ByteArray.fromHexString(privateKey), - CommonParameter.getInstance().isECKeyCryptoEngine()).getAddress())); + .fromPrivate(ByteArray.fromHexString(privateKey)).getAddress())); } // get active witnesses 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 8d56a2193f0..d435aee1207 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 @@ -298,7 +298,6 @@ private static void applyGenesisConfig(GenesisConfig gc, Config config) { * Bridge MiscConfig bean values to CommonParameter fields. */ private static void applyMiscConfig(MiscConfig mc) { - PARAMETER.cryptoEngine = mc.getCryptoEngine(); PARAMETER.needToUpdateAsset = mc.isNeedToUpdateAsset(); PARAMETER.historyBalanceLookup = mc.isHistoryBalanceLookup(); PARAMETER.trxReferenceBlock = mc.getTrxReferenceBlock(); @@ -695,11 +694,12 @@ private static void applyPlatformConstraints() { public static void applyConfigParams( final Config config) { + // Reject legacy crypto engines before storage or witness/keystore initialization. + miscConfig = MiscConfig.fromConfig(config); + Wallet.setAddressPreFixByte(ADD_PRE_FIX_BYTE_MAINNET); Wallet.setAddressPreFixString(Constant.ADD_PRE_FIX_STRING_MAINNET); - // crypto.engine handled by MiscConfig - // VM config: bind from config.conf "vm" section vmConfig = VmConfig.fromConfig(config); applyVmConfig(vmConfig); @@ -729,7 +729,6 @@ public static void applyConfigParams( // node discovery, legacy fallback, p2p, dns — all handled in applyNodeConfig // Misc config: storage, trx, energy — small domains, read via beans - miscConfig = MiscConfig.fromConfig(config); applyMiscConfig(miscConfig); // vm, committee already handled above diff --git a/framework/src/main/java/org/tron/core/config/args/WitnessInitializer.java b/framework/src/main/java/org/tron/core/config/args/WitnessInitializer.java index c2ce2ba0046..0ef43176790 100644 --- a/framework/src/main/java/org/tron/core/config/args/WitnessInitializer.java +++ b/framework/src/main/java/org/tron/core/config/args/WitnessInitializer.java @@ -36,8 +36,7 @@ public static LocalWitnesses initFromCLIPrivateKey( logger.debug("Got localWitnessAccountAddress from cmd"); } - witnesses.initWitnessAccountAddress( - address, Args.getInstance().isECKeyCryptoEngine()); + witnesses.initWitnessAccountAddress(address); logger.debug("Got privateKey from cmd"); return witnesses; } @@ -52,8 +51,7 @@ public static LocalWitnesses initFromCFGPrivateKey( logger.debug("Got privateKey from config.conf"); byte[] address = resolveWitnessAddress(witnesses, witnessAccountAddress); - witnesses.initWitnessAccountAddress( - address, Args.getInstance().isECKeyCryptoEngine()); + witnesses.initWitnessAccountAddress(address); return witnesses; } @@ -79,8 +77,7 @@ public static LocalWitnesses initFromKeystore( List privateKeys = new ArrayList<>(); try { - Credentials credentials = WalletUtils.loadCredentials(pwd, new File(fileName), - Args.getInstance().isECKeyCryptoEngine()); + Credentials credentials = WalletUtils.loadCredentials(pwd, new File(fileName)); SignInterface sign = credentials.getSignInterface(); String prikey = ByteArray.toHexString(sign.getPrivateKey()); privateKeys.add(prikey); @@ -106,8 +103,7 @@ public static LocalWitnesses initFromKeystore( LocalWitnesses witnesses = new LocalWitnesses(); witnesses.setPrivateKeys(privateKeys); byte[] address = resolveWitnessAddress(witnesses, witnessAccountAddress); - witnesses.initWitnessAccountAddress( - address, Args.getInstance().isECKeyCryptoEngine()); + witnesses.initWitnessAccountAddress(address); logger.debug("Got privateKey from keystore"); return witnesses; } diff --git a/framework/src/main/java/org/tron/core/consensus/ConsensusService.java b/framework/src/main/java/org/tron/core/consensus/ConsensusService.java index ef8f30ef498..b3921b1b657 100644 --- a/framework/src/main/java/org/tron/core/consensus/ConsensusService.java +++ b/framework/src/main/java/org/tron/core/consensus/ConsensusService.java @@ -49,8 +49,7 @@ public void start() { if (privateKeys.size() > 1) { for (String key : privateKeys) { byte[] privateKey = fromHexString(key); - byte[] privateKeyAddress = SignUtils - .fromPrivate(privateKey, Args.getInstance().isECKeyCryptoEngine()).getAddress(); + byte[] privateKeyAddress = SignUtils.fromPrivate(privateKey).getAddress(); WitnessCapsule witnessCapsule = witnessStore.get(privateKeyAddress); if (null == witnessCapsule) { logger.warn("Witness {} is not in witnessStore.", Hex.toHexString(privateKeyAddress)); @@ -64,8 +63,7 @@ public void start() { } else if (privateKeys.size() == 1) { byte[] privateKey = fromHexString(Args.getLocalWitnesses().getPrivateKey()); - byte[] privateKeyAddress = SignUtils.fromPrivate(privateKey, - Args.getInstance().isECKeyCryptoEngine()).getAddress(); + byte[] privateKeyAddress = SignUtils.fromPrivate(privateKey).getAddress(); byte[] witnessAddress = Args.getLocalWitnesses().getWitnessAccountAddress(); WitnessCapsule witnessCapsule = witnessStore.get(witnessAddress); if (null == witnessCapsule) { 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 9d7a7c979b9..e12075c658b 100644 --- a/framework/src/main/java/org/tron/core/db/Manager.java +++ b/framework/src/main/java/org/tron/core/db/Manager.java @@ -2638,8 +2638,7 @@ public TransactionInfoList getTransactionInfoByBlockNum(long blockNum) { List listTransaction = block.getTransactionsList(); for (Transaction transaction : listTransaction) { TransactionInfoCapsule transactionInfoCapsule = getTransactionHistoryStore() - .get(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); + .get(Sha256Hash.hash(transaction.getRawData().toByteArray())); if (transactionInfoCapsule != null) { transactionInfoList.addTransactionInfo(transactionInfoCapsule.getInstance()); diff --git a/framework/src/main/java/org/tron/core/net/messagehandler/PbftDataSyncHandler.java b/framework/src/main/java/org/tron/core/net/messagehandler/PbftDataSyncHandler.java index d66fa6d41f7..d7cbeacc796 100644 --- a/framework/src/main/java/org/tron/core/net/messagehandler/PbftDataSyncHandler.java +++ b/framework/src/main/java/org/tron/core/net/messagehandler/PbftDataSyncHandler.java @@ -130,7 +130,7 @@ private boolean validPbftSign(Raw raw, List srSignList, Param.getInstance().getAgreeNodeCount()); return false; } - byte[] dataHash = Sha256Hash.hash(true, raw.toByteArray()); + byte[] dataHash = Sha256Hash.hash(raw.toByteArray()); Set srSet = Sets.newHashSet(currentSrList); List> futureList = new ArrayList<>(); for (ByteString sign : srSignList) { diff --git a/framework/src/main/java/org/tron/core/net/service/relay/RelayService.java b/framework/src/main/java/org/tron/core/net/service/relay/RelayService.java index d4e010ff21d..c6810ef4167 100644 --- a/framework/src/main/java/org/tron/core/net/service/relay/RelayService.java +++ b/framework/src/main/java/org/tron/core/net/service/relay/RelayService.java @@ -109,13 +109,10 @@ public void fillHelloMessage(HelloMessage message, Channel channel) { fastForwardNodes.forEach(address -> { if (address.getAddress().equals(channel.getInetAddress())) { SignInterface cryptoEngine = SignUtils - .fromPrivate(ByteArray.fromHexString(Args.getLocalWitnesses().getPrivateKey()), - Args.getInstance().isECKeyCryptoEngine()); + .fromPrivate(ByteArray.fromHexString(Args.getLocalWitnesses().getPrivateKey())); ByteString sig = ByteString.copyFrom(cryptoEngine.Base64toBytes(cryptoEngine - .signHash(Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), ByteArray.fromLong(message - .getTimestamp())).getBytes()))); + .signHash(Sha256Hash.of(ByteArray.fromLong(message.getTimestamp())).getBytes()))); message.setHelloMessage(message.getHelloMessage().toBuilder() .setAddress(witnessAddress).setSignature(sig).build()); } @@ -158,12 +155,10 @@ public boolean checkHelloMessage(HelloMessage message, Channel channel) { boolean flag; try { - Sha256Hash hash = Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), ByteArray.fromLong(msg.getTimestamp())); + Sha256Hash hash = Sha256Hash.of(ByteArray.fromLong(msg.getTimestamp())); String sig = TransactionCapsule.getBase64FromByteString(msg.getSignature()); - byte[] sigAddress = SignUtils.signatureToAddress(hash.getBytes(), sig, - Args.getInstance().isECKeyCryptoEngine()); + byte[] sigAddress = SignUtils.signatureToAddress(hash.getBytes(), sig); if (manager.getDynamicPropertiesStore().getAllowMultiSign() != 1) { flag = Arrays.equals(sigAddress, msg.getAddress().toByteArray()); } else { 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 b9cb05a3b14..4a6964e86bf 100755 --- a/framework/src/main/java/org/tron/core/services/RpcApiService.java +++ b/framework/src/main/java/org/tron/core/services/RpcApiService.java @@ -263,8 +263,7 @@ private TransactionExtention transaction2Extention(Transaction transaction) { TransactionExtention.Builder trxExtBuilder = TransactionExtention.newBuilder(); Return.Builder retBuilder = Return.newBuilder(); trxExtBuilder.setTransaction(transaction); - trxExtBuilder.setTxid(Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getByteString()); + trxExtBuilder.setTxid(Sha256Hash.of(transaction.getRawData().toByteArray()).getByteString()); retBuilder.setResult(true).setCode(response_code.SUCCESS); trxExtBuilder.setResult(retBuilder); return trxExtBuilder.build(); 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 ca20902c4d8..3a30c152fdd 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 @@ -260,9 +260,7 @@ public static String printTransactionApprovedList(TransactionApprovedList transa public static byte[] generateContractAddress(Transaction trx, byte[] ownerAddress) { // get tx hash - byte[] txRawDataHash = Sha256Hash - .of(CommonParameter.getInstance().isECKeyCryptoEngine(), trx.getRawData().toByteArray()) - .getBytes(); + byte[] txRawDataHash = Sha256Hash.of(trx.getRawData().toByteArray()).getBytes(); // combine byte[] combined = new byte[txRawDataHash.length + ownerAddress.length]; @@ -319,9 +317,7 @@ public static JSONObject printTransactionToJSON(Transaction transaction, boolean jsonTransaction.put("raw_data", rawData); String rawDataHex = ByteArray.toHexString(transaction.getRawData().toByteArray()); jsonTransaction.put("raw_data_hex", rawDataHex); - String txID = ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); + String txID = ByteArray.toHexString(Sha256Hash.hash(transaction.getRawData().toByteArray())); jsonTransaction.put("txID", txID); return jsonTransaction; } diff --git a/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/RpcApiServiceOnSolidity.java b/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/RpcApiServiceOnSolidity.java index 315d70df8d6..32c2268ba7f 100755 --- a/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/RpcApiServiceOnSolidity.java +++ b/framework/src/main/java/org/tron/core/services/interfaceOnSolidity/RpcApiServiceOnSolidity.java @@ -33,7 +33,6 @@ import org.tron.api.GrpcAPI.WitnessList; import org.tron.api.WalletSolidityGrpc.WalletSolidityImplBase; import org.tron.common.application.RpcService; -import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.Sha256Hash; import org.tron.core.capsule.BlockCapsule; import org.tron.core.config.args.Args; @@ -85,8 +84,7 @@ private TransactionExtention transaction2Extention(Transaction transaction) { TransactionExtention.Builder trxExtBuilder = TransactionExtention.newBuilder(); Return.Builder retBuilder = Return.newBuilder(); trxExtBuilder.setTransaction(transaction); - trxExtBuilder.setTxid(Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()).getByteString()); + trxExtBuilder.setTxid(Sha256Hash.of(transaction.getRawData().toByteArray()).getByteString()); retBuilder.setResult(true).setCode(response_code.SUCCESS); trxExtBuilder.setResult(retBuilder); return trxExtBuilder.build(); diff --git a/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcApiUtil.java b/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcApiUtil.java index f4bba9fbf37..bd13f998112 100644 --- a/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcApiUtil.java +++ b/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcApiUtil.java @@ -15,7 +15,6 @@ import org.tron.api.GrpcAPI.AssetIssueList; import org.tron.common.crypto.Hash; import org.tron.common.math.StrictMathWrapper; -import org.tron.common.parameter.CommonParameter; import org.tron.common.runtime.vm.DataWord; import org.tron.common.utils.ByteArray; import org.tron.common.utils.ByteUtil; @@ -113,7 +112,7 @@ public static TriggerSmartContract triggerCallContract(byte[] address, byte[] co public static String getBlockID(Block block) { long blockNum = block.getBlockHeader().getRawData().getNumber(); - byte[] blockHash = Sha256Hash.of(true, block.getBlockHeader().getRawData().toByteArray()) + byte[] blockHash = Sha256Hash.of(block.getBlockHeader().getRawData().toByteArray()) .getByteString().toByteArray(); byte[] numBytes = Longs.toByteArray(blockNum); byte[] hash = new byte[blockHash.length]; @@ -215,7 +214,7 @@ public static List getTo(Transaction transaction) { } public static String getTxID(Transaction transaction) { - return ByteArray.toHexString(Sha256Hash.hash(true, transaction.getRawData().toByteArray())); + return ByteArray.toHexString(Sha256Hash.hash(transaction.getRawData().toByteArray())); } public static long getTransactionAmount(Transaction.Contract contract, String hash, @@ -556,9 +555,7 @@ public static long parseQuantityValue(String value) throws JsonRpcInvalidParamsE public static long getEnergyUsageTotal(Transaction transaction, Wallet wallet) { long energyUsageTotal = 0; - byte[] txHash = Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()); + byte[] txHash = Sha256Hash.hash(transaction.getRawData().toByteArray()); TransactionInfo transactionInfo = wallet .getTransactionInfoById(ByteString.copyFrom(txHash)); if (transactionInfo != null) { diff --git a/framework/src/main/java/org/tron/core/services/jsonrpc/types/BlockResult.java b/framework/src/main/java/org/tron/core/services/jsonrpc/types/BlockResult.java index f5f8fb7fdef..23ccbef5798 100644 --- a/framework/src/main/java/org/tron/core/services/jsonrpc/types/BlockResult.java +++ b/framework/src/main/java/org/tron/core/services/jsonrpc/types/BlockResult.java @@ -141,9 +141,7 @@ public BlockResult(Block block, boolean fullTx, Wallet wallet) { gasLimitInBlock += transactionsList.get(i).getRawData().getFeeLimit(); gasUsedInBlock += getEnergyUsageTotal(transactionInfoList, i, blockCapsule.getNum()); - byte[] txHash = Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transactionsList.get(i).getRawData().toByteArray()); + byte[] txHash = Sha256Hash.hash(transactionsList.get(i).getRawData().toByteArray()); txes.add(ByteArray.toJsonHex(txHash)); } } @@ -153,4 +151,4 @@ public BlockResult(Block block, boolean fullTx, Wallet wallet) { gasUsed = ByteArray.toJsonHex(gasUsedInBlock); uncles = new String[0]; } -} \ No newline at end of file +} diff --git a/framework/src/main/java/org/tron/core/zen/ShieldedTRC20ParametersBuilder.java b/framework/src/main/java/org/tron/core/zen/ShieldedTRC20ParametersBuilder.java index 4ee4f75a171..4bef932971d 100644 --- a/framework/src/main/java/org/tron/core/zen/ShieldedTRC20ParametersBuilder.java +++ b/framework/src/main/java/org/tron/core/zen/ShieldedTRC20ParametersBuilder.java @@ -343,7 +343,7 @@ public ShieldedTRC20Parameters build(boolean withAsk) throws ZksnarkException { throw new ZksnarkException("unknown parameters type"); } - dataHashToBeSigned = Sha256Hash.of(true, mergedBytes).getBytes(); + dataHashToBeSigned = Sha256Hash.of(mergedBytes).getBytes(); if (dataHashToBeSigned == null) { throw new ZksnarkException("calculate transaction hash failed"); } diff --git a/framework/src/main/java/org/tron/program/KeystoreFactory.java b/framework/src/main/java/org/tron/program/KeystoreFactory.java index f4e26afa145..19dfd9bfef4 100755 --- a/framework/src/main/java/org/tron/program/KeystoreFactory.java +++ b/framework/src/main/java/org/tron/program/KeystoreFactory.java @@ -8,7 +8,6 @@ import org.apache.commons.lang3.StringUtils; import org.tron.common.crypto.SignInterface; import org.tron.common.crypto.SignUtils; -import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; import org.tron.common.utils.Utils; import org.tron.core.exception.CipherException; @@ -67,16 +66,14 @@ private void fileCheck(File file) throws IOException { private void genKeystore() throws CipherException, IOException { - boolean ecKey = CommonParameter.getInstance().isECKeyCryptoEngine(); String password = WalletUtils.inputPassword2Twice(); - SignInterface eCkey = SignUtils.getGeneratedRandomSign(Utils.random, ecKey); + SignInterface eCkey = SignUtils.getGeneratedRandomSign(Utils.random); File file = new File(FilePath); fileCheck(file); String fileName = WalletUtils.generateWalletFile(password, eCkey, file, true); System.out.println("Gen a keystore its name " + fileName); - Credentials credentials = WalletUtils.loadCredentials(password, new File(file, fileName), - ecKey); + Credentials credentials = WalletUtils.loadCredentials(password, new File(file, fileName)); System.out.println("Your address is " + credentials.getAddress()); } @@ -95,14 +92,12 @@ private void importPrivateKey() throws CipherException, IOException { String password = WalletUtils.inputPassword2Twice(); - boolean ecKey = CommonParameter.getInstance().isECKeyCryptoEngine(); - SignInterface eCkey = SignUtils.fromPrivate(ByteArray.fromHexString(privateKey), ecKey); + SignInterface eCkey = SignUtils.fromPrivate(ByteArray.fromHexString(privateKey)); File file = new File(FilePath); fileCheck(file); String fileName = WalletUtils.generateWalletFile(password, eCkey, file, true); System.out.println("Gen a keystore its name " + fileName); - Credentials credentials = WalletUtils.loadCredentials(password, new File(file, fileName), - ecKey); + Credentials credentials = WalletUtils.loadCredentials(password, new File(file, fileName)); System.out.println("Your address is " + credentials.getAddress()); } @@ -159,4 +154,4 @@ private void run() { } } } -} \ No newline at end of file +} diff --git a/framework/src/main/resources/config.conf b/framework/src/main/resources/config.conf index 1176dd46311..c0bed931d13 100644 --- a/framework/src/main/resources/config.conf +++ b/framework/src/main/resources/config.conf @@ -63,11 +63,6 @@ node.backup { ] } -# Specify the algorithm for generating a public key from private key. To avoid forks, please do not modify it -crypto { - engine = "eckey" -} - node.metrics = { prometheus { enable = false diff --git a/framework/src/test/java/org/tron/common/BaseTest.java b/framework/src/test/java/org/tron/common/BaseTest.java index 471aaa3d383..bef288de7f1 100644 --- a/framework/src/test/java/org/tron/common/BaseTest.java +++ b/framework/src/test/java/org/tron/common/BaseTest.java @@ -138,8 +138,7 @@ public Protocol.Block getSignedBlock(ByteString witness, long time, byte[] priva ECKey ecKey = ECKey.fromPrivate(privateKey); assert ecKey != null; - ECKey.ECDSASignature signature = ecKey.sign(Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), raw.toByteArray()).getBytes()); + ECKey.ECDSASignature signature = ecKey.sign(Sha256Hash.of(raw.toByteArray()).getBytes()); ByteString sign = ByteString.copyFrom(signature.toByteArray()); Protocol.BlockHeader blockHeader = block.getBlockHeader().toBuilder() diff --git a/framework/src/test/java/org/tron/common/ParameterTest.java b/framework/src/test/java/org/tron/common/ParameterTest.java index 0b66c96462c..c65b5566c9e 100644 --- a/framework/src/test/java/org/tron/common/ParameterTest.java +++ b/framework/src/test/java/org/tron/common/ParameterTest.java @@ -7,7 +7,6 @@ import static org.junit.Assert.assertTrue; import static org.tron.common.parameter.RateLimiterInitialization.createHttpItem; import static org.tron.common.parameter.RateLimiterInitialization.createRpcItem; -import static org.tron.core.Constant.ECKey_ENGINE; import com.google.common.collect.Lists; import com.typesafe.config.ConfigFactory; @@ -216,8 +215,6 @@ public void testCommonParameter() { assertEquals(100, parameter.getRateLimiterGlobalIpQps()); assertNull(parameter.getEventPluginConfig()); assertNull(parameter.getEventFilter()); - parameter.setCryptoEngine(ECKey_ENGINE); - assertEquals(ECKey_ENGINE, parameter.getCryptoEngine()); parameter.setFullNodeHttpEnable(false); assertFalse(parameter.isFullNodeHttpEnable()); parameter.setSolidityNodeHttpEnable(false); diff --git a/framework/src/test/java/org/tron/common/crypto/BouncyCastleTest.java b/framework/src/test/java/org/tron/common/crypto/BouncyCastleTest.java index ab6b2832c12..f361117f712 100644 --- a/framework/src/test/java/org/tron/common/crypto/BouncyCastleTest.java +++ b/framework/src/test/java/org/tron/common/crypto/BouncyCastleTest.java @@ -7,11 +7,9 @@ import java.math.BigInteger; import java.security.SignatureException; import java.util.Arrays; -import org.bouncycastle.crypto.digests.SM3Digest; import org.bouncycastle.util.encoders.Hex; import org.junit.Assert; import org.junit.Test; -import org.tron.common.crypto.sm2.SM2; import org.tron.common.utils.Sha256Hash; /** @@ -40,11 +38,8 @@ public void testHex() { public void testSha256Hash() { String msg = "transaction raw data"; String spongySha256 = "da36dc042630f1aa810171d1fc4db7771a9f12b585848b0fed6caf5c7bd06531"; - String spongySm3 = "5521fbff5abf495e6db8fb4a83ed2bf27b97197757fc5a1002a7edc58b690900"; - byte[] sha256Hash = Sha256Hash.hash(true, msg.getBytes()); + byte[] sha256Hash = Sha256Hash.hash(msg.getBytes()); assertEquals(spongySha256, Hex.toHexString(sha256Hash)); - byte[] sm3Hash = Sha256Hash.hash(false, msg.getBytes()); - assertEquals(spongySm3, Hex.toHexString(sm3Hash)); } @Test @@ -70,12 +65,12 @@ public void testECKeyAddress() { @Test public void testECKeySignature() throws SignatureException { - SignInterface sign = SignUtils.fromPrivate(Hex.decode(privString), true); + SignInterface sign = SignUtils.fromPrivate(Hex.decode(privString)); String msg = "transaction raw data"; String spongyAddress = "2e988a386a799f506693793c6a5af6b54dfaabfb"; - byte[] hash = Sha256Hash.hash(true, msg.getBytes()); + byte[] hash = Sha256Hash.hash(msg.getBytes()); String sig = sign.signHash(hash); - byte[] address = SignUtils.signatureToAddress(hash, sig, true); + byte[] address = SignUtils.signatureToAddress(hash, sig); assertEquals(spongyAddress, Hex.toHexString(Arrays.copyOfRange(address, 1, 21))); } @@ -85,52 +80,8 @@ public void testECSpongySignature() throws SignatureException { String spongySig = "GwYii3BGoQq3sdyWiGVv7bGCR5hJy62g+IF+1jPOSqHt" + "IDfuKgowhiiK7ivcqk+T7qq/hlfIjaRe+t1drFDZ+Mo="; String spongyAddress = "cd2a3d9f938e13cd947ec05abc7fe734df8dd826"; - byte[] hash = Sha256Hash.hash(true, msg.getBytes()); - byte[] address = SignUtils.signatureToAddress(hash, spongySig, true); - assertEquals(spongyAddress, Hex.toHexString(Arrays.copyOfRange(address, 1, 21))); - } - - @Test - public void testSM3Hash() { - String msg = "transaction raw data"; - String spongyHash = "5521fbff5abf495e6db8fb4a83ed2bf27b97197757fc5a1002a7edc58b690900"; - SM3Digest digest = new SM3Digest(); - digest.update(msg.getBytes(), 0, msg.getBytes().length); - byte[] hash = new byte[digest.getDigestSize()]; - digest.doFinal(hash, 0); - assertEquals(spongyHash, Hex.toHexString(hash)); - } - - @Test - public void testSM2Address() { - String spongyPublickey = "04dc3547dbbc4c90a9cde599848e26cb145e805b3d11daaf9daae0680d9c6824058ac" - + "35ddecb12f3a8bbc3104a2b91a2b7d04851d773d9b4ab8d5e0359243c8628"; - String spongyAddress = "6cb22f88564bdd61eb4cdb36215add53bc702ff1"; - SM2 key = SM2.fromPrivate(privateKey); - assertEquals(spongyPublickey, Hex.toHexString(key.getPubKey())); - byte[] address = key.getAddress(); - assertEquals(spongyAddress, Hex.toHexString(Arrays.copyOfRange(address, 1, 21))); - } - - @Test - public void testSM2Signature() throws SignatureException { - SignInterface sign = SignUtils.fromPrivate(Hex.decode(privString), false); - String msg = "transaction raw data"; - String spongyAddress = "6cb22f88564bdd61eb4cdb36215add53bc702ff1"; - byte[] hash = Sha256Hash.hash(false, msg.getBytes()); - String sig = sign.signHash(hash); - byte[] address = SignUtils.signatureToAddress(hash, sig, false); - assertEquals(spongyAddress, Hex.toHexString(Arrays.copyOfRange(address, 1, 21))); - } - - @Test - public void testSM2SpongySignature() throws SignatureException { - String msg = "transaction raw data"; - String spongySig = "HOoyvBLOJ+dKReQdAc6W/ffRi/KmVntco0+xgzmFItEExq/fHF" - + "veCe0GoCJUBdyHyUFjwn+a18ibtGJcHxnvLj0="; - String spongyAddress = "7dc44d739a5226c0d3037bb7919f653eb2f938b9"; - byte[] hash = Sha256Hash.hash(false, msg.getBytes()); - byte[] address = SignUtils.signatureToAddress(hash, spongySig, false); + byte[] hash = Sha256Hash.hash(msg.getBytes()); + byte[] address = SignUtils.signatureToAddress(hash, spongySig); assertEquals(spongyAddress, Hex.toHexString(Arrays.copyOfRange(address, 1, 21))); } @@ -140,12 +91,7 @@ public void testSignToAddress() { String base64Sign = "G1y76mVO6TRpFwp3qOiLVzHA8uFsrDiOL7hbC2uN9qTHHiLypaW4vnQkfkoUygjo5qBd" + "+NlYQ/mAPVWKu6K00co="; try { - SignUtils.signatureToAddress(Hex.decode(messageHash), base64Sign, Boolean.TRUE); - } catch (Exception e) { - Assert.assertTrue(e instanceof SignatureException); - } - try { - SignUtils.signatureToAddress(Hex.decode(messageHash), base64Sign, Boolean.FALSE); + SignUtils.signatureToAddress(Hex.decode(messageHash), base64Sign); } catch (Exception e) { Assert.assertTrue(e instanceof SignatureException); } diff --git a/framework/src/test/java/org/tron/common/crypto/SM2KeyTest.java b/framework/src/test/java/org/tron/common/crypto/SM2KeyTest.java deleted file mode 100644 index b8507256ba3..00000000000 --- a/framework/src/test/java/org/tron/common/crypto/SM2KeyTest.java +++ /dev/null @@ -1,285 +0,0 @@ -package org.tron.common.crypto; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.tron.common.utils.client.utils.AbiUtil.generateOccupationConstantPrivateKey; - -import java.math.BigInteger; -import java.security.KeyPairGenerator; -import java.security.SignatureException; -import java.util.Arrays; -import java.util.Locale; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.crypto.digests.SM3Digest; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Test; -import org.tron.common.crypto.sm2.SM2; -import org.tron.common.crypto.sm2.SM2Signer; -import org.tron.core.Wallet; - -/** - * The reason the test case uses the private key plaintext is to ensure that, - * after the ECkey tool or algorithm is upgraded, - * the upgraded differences can be verified. - */ -@Slf4j -public class SM2KeyTest { - - //private String IDa = "ALICE123@YAHOO.COM"; - private static BigInteger SM2_N = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6" - + "B21C6052B53BBF40939D54123", 16); - // For safety reasons, test with a placeholder private key - private String privString = generateOccupationConstantPrivateKey(); - private BigInteger privateKey = new BigInteger(privString, 16); - private String pubString = "04dc3547dbbc4c90a9cde599848e26cb145e805b3d11daaf9daae0680d9c6824058ac" - + "35ddecb12f3a8bbc3104a2b91a2b7d04851d773d9b4ab8d5e0359243c8628"; - private String compressedPubString = - "02dc3547dbbc4c90a9cde599848e26cb145e805b3d11daaf9daae0680d9c682405"; - private byte[] pubKey = Hex.decode(pubString); - private byte[] compressedPubKey = Hex.decode(compressedPubString); - private String address = "6cb22f88564bdd61eb4cdb36215add53bc702ff1"; - - @Test - public void testHashCode() { - assertEquals(578690511, SM2.fromPrivate(privateKey).hashCode()); - } - - @Test - public void testSM2() { - SM2 key = new SM2(); - assertTrue(key.isPubKeyCanonical()); - assertNotNull(key.getPubKey()); - assertNotNull(key.getPrivKeyBytes()); - logger.info(Hex.toHexString(key.getPrivKeyBytes()) + " :Generated privkey"); - logger.info(Hex.toHexString(key.getPubKey()) + " :Generated pubkey"); - logger.info("private key in bigInteger form: " + key.getPrivKey()); - } - - @Test - public void testFromPrivateKey() { - SM2 key = SM2.fromPrivate(privateKey); - assertTrue(key.isPubKeyCanonical()); - assertTrue(key.hasPrivKey()); - assertArrayEquals(pubKey, key.getPubKey()); - - key = SM2.fromPrivate((byte[]) null); - assertNull(key); - key = SM2.fromPrivate(new byte[0]); - assertNull(key); - } - - @Test(expected = IllegalArgumentException.class) - public void testPrivatePublicKeyBytesNoArg() { - new SM2((BigInteger) null, null); - fail("Expecting an IllegalArgumentException for using only null-parameters"); - } - - @Test(expected = IllegalArgumentException.class) - public void testInvalidPrivateKey() throws Exception { - new SM2( - KeyPairGenerator.getInstance("RSA").generateKeyPair().getPrivate(), - SM2.fromPublicOnly(pubKey).getPubKeyPoint()); - fail("Expecting an IllegalArgumentException for using an non EC private key"); - } - - @Test - public void testIsPubKeyOnly() { - SM2 key = SM2.fromPublicOnly(pubKey); - assertTrue(key.isPubKeyCanonical()); - assertTrue(key.isPubKeyOnly()); - assertArrayEquals(key.getPubKey(), pubKey); - } - - @Test(expected = IllegalArgumentException.class) - public void testSignIncorrectInputSize() { - SM2 key = new SM2(); - String message = "The quick brown fox jumps over the lazy dog."; - SM2.SM2Signature sig = key.sign(message.getBytes()); - fail("Expecting an IllegalArgumentException for a non 32-byte input"); - } - - @Test(expected = SignatureException.class) - public void testBadBase64Sig() throws SignatureException { - byte[] messageHash = new byte[32]; - SM2.signatureToKey(messageHash, "This is not valid Base64!"); - fail("Expecting a SignatureException for invalid Base64"); - } - - @Test(expected = SignatureException.class) - public void testInvalidSignatureLength() throws SignatureException { - byte[] messageHash = new byte[32]; - SM2.signatureToKey(messageHash, "abcdefg"); - fail("Expecting a SignatureException for invalid signature length"); - } - - @Test - public void testSM3Hash() { - SM2 key = SM2.fromPublicOnly(pubKey); - SM2Signer signer = key.getSM2SignerForHash(); - String message = "message digest"; - byte[] hash = signer.generateSM3Hash(message.getBytes()); - assertEquals("2A723761EAE35429DF643648FD69FB7787E7FC32F321BFAF7E294390F529BAF4", - Hex.toHexString(hash).toUpperCase(Locale.ROOT)); - } - - - @Test - public void testSignatureToKeyBytes() throws SignatureException { - SM2 key = SM2.fromPrivate(privateKey); - byte[] hash = Hex.decode("B524F552CD82B8B028476E005C377FB" - + "19A87E6FC682D48BB5D42E3D9B9EFFE76"); - SM2.SM2Signature sign = key.sign(hash); - byte[] pubKeys = SM2.signatureToKeyBytes(hash, sign); - assertEquals(Hex.toHexString(pubKey), Hex.toHexString(pubKeys)); - } - - @Test - public void testSignatureToKeyBytes2() throws SignatureException { - SM2 key = SM2.fromPrivate(privateKey); - byte[] hash = Hex.decode("B524F552CD82B8B028476E005C377FB" - + "19A87E6FC682D48BB5D42E3D9B9EFFE76"); - SM2.SM2Signature sign = key.sign(hash); - byte[] pubKeys = SM2.signatureToKeyBytes(hash, sign); - assertArrayEquals(pubKeys, key.getPubKey()); - } - - @Test - public void testSignatureToAddress() throws SignatureException { - SM2 key = SM2.fromPrivate(privateKey); - byte[] hash = Hex.decode("B524F552CD82B8B028476E005C377FB" - + "19A87E6FC682D48BB5D42E3D9B9EFFE76"); - SM2.SM2Signature sign = key.sign(hash); - byte[] addr = SM2.signatureToAddress(hash, sign); - addr = Arrays.copyOfRange(addr, 1, addr.length); - assertEquals(address, Hex.toHexString(addr)); - } - - @Test - public void testPublicKeyFromPrivate() { - byte[] pubFromPriv = SM2.publicKeyFromPrivate(privateKey, false); - assertArrayEquals(pubKey, pubFromPriv); - } - - @Test - public void testPublicKeyFromPrivateCompressed() { - byte[] pubFromPriv = SM2.publicKeyFromPrivate(privateKey, true); - assertArrayEquals(compressedPubKey, pubFromPriv); - } - - @Test - public void testGetAddress() { - SM2 key = SM2.fromPublicOnly(pubKey); - byte[] prefixedAddress = key.getAddress(); - byte[] unprefixedAddress = Arrays.copyOfRange(key.getAddress(), 1, prefixedAddress.length); - assertArrayEquals(Hex.decode(address), unprefixedAddress); - assertEquals(Wallet.getAddressPreFixByte(), prefixedAddress[0]); - } - - @Test - public void testGetAddressFromPrivateKey() { - SM2 key = SM2.fromPrivate(privateKey); - byte[] prefixedAddress = key.getAddress(); - byte[] unprefixedAddress = Arrays.copyOfRange(key.getAddress(), 1, prefixedAddress.length); - assertArrayEquals(Hex.decode(address), unprefixedAddress); - assertEquals(Wallet.getAddressPreFixByte(), prefixedAddress[0]); - } - - @Test - public void testToString() { - SM2 key = SM2.fromPrivate(BigInteger.TEN); // An example private key. - assertEquals("pub:04d3f94862519621c121666061f65c3e32b2d0d065" - + "cd219e3284a04814db5227564b9030cf676f6a742ebd57d146dca" - + "428f6b743f64d1482d147d46fb2bab82a14", key.toString()); - } - - @Test - public void testIsPubKeyCanonicalCorrect() { - // Test correct prefix 4, right length 65 - byte[] canonicalPubkey1 = new byte[65]; - canonicalPubkey1[0] = 0x04; - assertTrue(SM2.isPubKeyCanonical(canonicalPubkey1)); - // Test correct prefix 2, right length 33 - byte[] canonicalPubkey2 = new byte[33]; - canonicalPubkey2[0] = 0x02; - assertTrue(SM2.isPubKeyCanonical(canonicalPubkey2)); - // Test correct prefix 3, right length 33 - byte[] canonicalPubkey3 = new byte[33]; - canonicalPubkey3[0] = 0x03; - assertTrue(SM2.isPubKeyCanonical(canonicalPubkey3)); - } - - @Test - public void testIsPubKeyCanonicalWrongLength() { - // Test correct prefix 4, but wrong length !65 - byte[] nonCanonicalPubkey1 = new byte[64]; - nonCanonicalPubkey1[0] = 0x04; - assertFalse(SM2.isPubKeyCanonical(nonCanonicalPubkey1)); - // Test correct prefix 2, but wrong length !33 - byte[] nonCanonicalPubkey2 = new byte[32]; - nonCanonicalPubkey2[0] = 0x02; - assertFalse(SM2.isPubKeyCanonical(nonCanonicalPubkey2)); - // Test correct prefix 3, but wrong length !33 - byte[] nonCanonicalPubkey3 = new byte[32]; - nonCanonicalPubkey3[0] = 0x03; - assertFalse(SM2.isPubKeyCanonical(nonCanonicalPubkey3)); - } - - @Test - public void testIsPubKeyCanonicalWrongPrefix() { - // Test wrong prefix 4, right length 65 - byte[] nonCanonicalPubkey4 = new byte[65]; - assertFalse(SM2.isPubKeyCanonical(nonCanonicalPubkey4)); - // Test wrong prefix 2, right length 33 - byte[] nonCanonicalPubkey5 = new byte[33]; - assertFalse(SM2.isPubKeyCanonical(nonCanonicalPubkey5)); - // Test wrong prefix 3, right length 33 - byte[] nonCanonicalPubkey6 = new byte[33]; - assertFalse(SM2.isPubKeyCanonical(nonCanonicalPubkey6)); - } - - @Test - public void testGetPrivKeyBytes() { - SM2 key = new SM2(); - assertNotNull(key.getPrivKeyBytes()); - assertEquals(32, key.getPrivKeyBytes().length); - } - - @Test - public void testEqualsObject() { - SM2 key0 = new SM2(); - SM2 key1 = SM2.fromPrivate(privateKey); - SM2 key2 = SM2.fromPrivate(privateKey); - - assertFalse(key0.equals(key1)); - assertTrue(key1.equals(key1)); - assertTrue(key1.equals(key2)); - } - - @Test - public void testNodeId() { - SM2 key = SM2.fromPublicOnly(pubKey); - - assertEquals(key, SM2.fromNodeId(key.getNodeId())); - } - - @Test - public void testSM3() { - String message = "F4A38489E32B45B6F876E3AC2168CA392362DC8F23459C1D1146F" - + "C3DBFB7BC9A6D65737361676520646967657374"; - SM3Digest digest = new SM3Digest(); - byte[] msg = Hex.decode(message); - digest.update(msg, 0, msg.length); - - byte[] eHash = new byte[digest.getDigestSize()]; - - digest.doFinal(eHash, 0); - - assertEquals("b524f552cd82b8b028476e005c377fb19a87e6fc682d48bb5d42e3d9b9effe76", - Hex.toHexString(eHash)); - } -} diff --git a/framework/src/test/java/org/tron/common/crypto/SignatureInterfaceTest.java b/framework/src/test/java/org/tron/common/crypto/SignatureInterfaceTest.java index b413127db53..c8128f3059e 100644 --- a/framework/src/test/java/org/tron/common/crypto/SignatureInterfaceTest.java +++ b/framework/src/test/java/org/tron/common/crypto/SignatureInterfaceTest.java @@ -7,20 +7,12 @@ import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; import org.junit.Test; -import org.tron.common.crypto.sm2.SM2; import org.tron.common.utils.PublicMethod; @Slf4j public class SignatureInterfaceTest { - private String SM2_privString = PublicMethod.getSM2RandomPrivateKey(); - private byte[] SM2_privateKey = Hex.decode(SM2_privString); - - private String SM2_pubString = PublicMethod.getSM2PublicByPrivateKey(SM2_privString); - private byte[] SM2_pubKey = Hex.decode(SM2_pubString); - private String SM2_address = PublicMethod.getSM2AddressByPrivateKey(SM2_privString); - private String EC_privString = PublicMethod.getRandomPrivateKey(); private byte[] EC_privateKey = Hex.decode(EC_privString); @@ -28,57 +20,36 @@ public class SignatureInterfaceTest { private byte[] EC_pubKey = Hex.decode(EC_pubString); private String EC_address = PublicMethod.getHexAddressByPrivateKey(EC_privString); - - @Test public void testContructor() { - SignInterface sign = new SM2(); - logger.info(Hex.toHexString(sign.getPrivateKey()) + " :SM2 Generated privkey"); - logger.info(Hex.toHexString(sign.getPubKey()) + " :SM2 Generated pubkey"); - - sign = new ECKey(); + SignInterface sign = new ECKey(); logger.info(Hex.toHexString(sign.getPrivateKey()) + " :ECDSA Generated privkey"); logger.info(Hex.toHexString(sign.getPubKey()) + " :ECDSA Generated pubkey"); } @Test public void testPirvateKey() { - SignInterface sign = new SM2(SM2_privateKey, true); - assertArrayEquals(sign.getPubKey(), SM2_pubKey); - - sign = new ECKey(EC_privateKey, true); + SignInterface sign = new ECKey(EC_privateKey, true); assertArrayEquals(sign.getPubKey(), EC_pubKey); - } @Test public void testPublicKey() { - SignInterface sign = new SM2(SM2_pubKey, false); - assertArrayEquals(sign.getPubKey(), SM2_pubKey); - - sign = new ECKey(EC_pubKey, false); + SignInterface sign = new ECKey(EC_pubKey, false); assertArrayEquals(sign.getPubKey(), EC_pubKey); } @Test public void testNullKey() { - SignInterface sign = new SM2(SM2_pubKey, false); - assertEquals(null, sign.getPrivateKey()); - - sign = new ECKey(EC_pubKey, false); + SignInterface sign = new ECKey(EC_pubKey, false); assertEquals(null, sign.getPrivateKey()); } @Test public void testAddress() { - SignInterface sign = new SM2(SM2_pubKey, false); + SignInterface sign = new ECKey(EC_pubKey, false); byte[] prefix_address = sign.getAddress(); byte[] address = Arrays.copyOfRange(prefix_address, 1, prefix_address.length); - byte[] addressTmp = Arrays.copyOfRange(Hex.decode(SM2_address), 1, prefix_address.length); - assertEquals(Hex.toHexString(addressTmp), Hex.toHexString(address)); - sign = new ECKey(EC_pubKey, false); - prefix_address = sign.getAddress(); - address = Arrays.copyOfRange(prefix_address, 1, prefix_address.length); byte[] ecAddressTmp = Arrays.copyOfRange(Hex.decode(EC_address), 1, prefix_address.length); assertEquals(Hex.toHexString(ecAddressTmp), Hex.toHexString(address)); } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/ValidateMultiSignContractTest.java b/framework/src/test/java/org/tron/common/runtime/vm/ValidateMultiSignContractTest.java index d7ccab73bd9..15f5203a779 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/ValidateMultiSignContractTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/ValidateMultiSignContractTest.java @@ -15,7 +15,6 @@ import org.tron.common.TestConstants; import org.tron.common.crypto.ECKey; import org.tron.common.crypto.Hash; -import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; import org.tron.common.utils.ByteUtil; import org.tron.common.utils.Sha256Hash; @@ -103,14 +102,12 @@ public void testDifferentCase() { byte[] address = key.getAddress(); int permissionId = 2; - byte[] data = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), longData); + byte[] data = Sha256Hash.hash(longData); //combine data byte[] merged = ByteUtil.merge(address, ByteArray.fromInt(permissionId), data); //sha256 of it - byte[] toSign = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), merged); + byte[] toSign = Sha256Hash.hash(merged); //sign data @@ -219,9 +216,9 @@ public void testTip854CanonicalInputUnchanged() { Collections.singletonList(activePermission)); dbManager.getAccountStore().put(key.getAddress(), toAccount); - byte[] data = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), longData); + byte[] data = Sha256Hash.hash(longData); byte[] merged = ByteUtil.merge(key.getAddress(), ByteArray.fromInt(2), data); - byte[] toSign = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), merged); + byte[] toSign = Sha256Hash.hash(merged); List signs = new ArrayList<>(); signs.add(Hex.toHexString(key1.sign(toSign).toByteArray())); signs.add(Hex.toHexString(key2.sign(toSign).toByteArray())); diff --git a/framework/src/test/java/org/tron/common/utils/PublicMethod.java b/framework/src/test/java/org/tron/common/utils/PublicMethod.java index 90a2aae3f76..7ffc44e936c 100644 --- a/framework/src/test/java/org/tron/common/utils/PublicMethod.java +++ b/framework/src/test/java/org/tron/common/utils/PublicMethod.java @@ -17,8 +17,6 @@ import org.tron.api.GrpcAPI; import org.tron.api.WalletGrpc; import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.sm2.SM2; -import org.tron.common.crypto.sm2.SM2Signer; import org.tron.common.utils.client.utils.TransactionUtils; import org.tron.core.Wallet; import org.tron.protos.Protocol; @@ -55,37 +53,6 @@ public static byte[] getPublicKeyFromPrivate(String privateKey) { return ECKey.publicKeyFromPrivate(tmpKey, true); } - public static String getSM2RandomPrivateKey() { - SM2 key = new SM2(Utils.getRandom()); - return Hex.toHexString( - Objects.requireNonNull(key.getPrivKeyBytes())); - } - - public static SM2 getSM2byPrivate(String privateKey) { - BigInteger priK = new BigInteger(privateKey, 16); - return SM2.fromPrivate(priK); - } - - public static String getSM2PublicByPrivateKey(String privateKey) { - return Hex.toHexString(getSM2byPrivate(privateKey).getPubKey()); - } - - public static String getSM2AddressByPrivateKey(String privateKey) { - return ByteArray - .toHexString(getSM2byPrivate(privateKey).getAddress()); - } - - public static byte[] getSM2PublicKeyFromPrivate(String privateKey) { - BigInteger tmpKey = new BigInteger(privateKey, 16); - return SM2.publicKeyFromPrivate(tmpKey, true); - } - - public static byte[] getSM2HashByPubKey(byte[] pubKey, String message) { - SM2 key = SM2.fromPublicOnly(pubKey); - SM2Signer signer = key.getSM2SignerForHash(); - return signer.generateSM3Hash(message.getBytes()); - } - /** constructor. */ public static SmartContractOuterClass.SmartContract.ABI jsonStr2Abi(String jsonStr) { if (jsonStr == null) { diff --git a/framework/src/test/java/org/tron/common/utils/Sha256HashTest.java b/framework/src/test/java/org/tron/common/utils/Sha256HashTest.java index 0df72cc125d..e8e03a42db6 100644 --- a/framework/src/test/java/org/tron/common/utils/Sha256HashTest.java +++ b/framework/src/test/java/org/tron/common/utils/Sha256HashTest.java @@ -5,18 +5,14 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import ch.qos.logback.core.util.FileUtil; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; -import java.nio.file.Files; import java.util.Arrays; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.IntStream; -import org.apache.commons.io.FileUtils; import org.junit.Assert; import org.junit.Test; -import org.tron.common.parameter.CommonParameter; public class Sha256HashTest { @@ -24,10 +20,8 @@ public class Sha256HashTest { public void testHash() throws IOException { //Example from https://github.com/tronprotocol/tips/blob/master/TWP-001.md byte[] input = ByteArray.fromHexString("A0E11973395042BA3C0B52B4CDF4E15EA77818F275"); - byte[] hash0 = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), input); - byte[] hash1 = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), hash0); + byte[] hash0 = Sha256Hash.hash(input); + byte[] hash1 = Sha256Hash.hash(hash0); assertEquals(Arrays.toString(hash0), Arrays.toString(ByteArray .fromHexString("CD5D4A7E8BE869C00E17F8F7712F41DBE2DDBD4D8EC36A7280CD578863717084"))); assertEquals(Arrays.toString(hash1), Arrays.toString(ByteArray @@ -36,22 +30,16 @@ public void testHash() throws IOException { Sha256Hash sha256Hash = new Sha256Hash(1, new byte[32]); assertNotNull(sha256Hash.toBigInteger()); - Sha256Hash.create(true, ("byte1-1").getBytes(StandardCharsets.UTF_8)); + Sha256Hash.create(("byte1-1").getBytes(StandardCharsets.UTF_8)); File testfile = createTempFile("testfile", ".txt").toFile(); - Sha256Hash.of(true, testfile); - Sha256Hash.createDouble(true, new byte[0]); - Sha256Hash.twiceOf(true, new byte[0]); - Sha256Hash.hashTwice(true, new byte[0]); - Sha256Hash.hashTwice(false, new byte[0]); - Sha256Hash.hashTwice(true, new byte[0], 0, 0); - Sha256Hash.hashTwice(false, new byte[0], 0, 0); - Sha256Hash.hash(false, new byte[0], 0, 0); - Sha256Hash.hashTwice(true, new byte[0], 0, 0, new byte[0], 0, 0); - Sha256Hash.hashTwice(false, new byte[0], 0, 0, new byte[0], 0, 0); + Sha256Hash.of(testfile); + Sha256Hash.createDouble(new byte[0]); + Sha256Hash.twiceOf(new byte[0]); + Sha256Hash.hashTwice(new byte[0]); + Sha256Hash.hashTwice(new byte[0], 0, 0); + Sha256Hash.hash(new byte[0], 0, 0); + Sha256Hash.hashTwice(new byte[0], 0, 0, new byte[0], 0, 0); assertTrue(testfile.delete()); - - - } @Test @@ -65,8 +53,7 @@ public void testMultiThreadingHash() { Thread thread = new Thread(() -> { for (int i = 0; i < 10000; i++) { - byte[] hash0 = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), input); + byte[] hash0 = Sha256Hash.hash(input); countAll.incrementAndGet(); if (!Arrays.equals(hash, hash0)) { countFailed.incrementAndGet(); @@ -84,4 +71,4 @@ public void testMultiThreadingHash() { assertEquals(70000, countAll.get()); assertEquals(0, countFailed.get()); } -} \ No newline at end of file +} diff --git a/framework/src/test/java/org/tron/common/utils/client/WalletClient.java b/framework/src/test/java/org/tron/common/utils/client/WalletClient.java index 9d9a68da49d..b1816eff657 100644 --- a/framework/src/test/java/org/tron/common/utils/client/WalletClient.java +++ b/framework/src/test/java/org/tron/common/utils/client/WalletClient.java @@ -474,10 +474,8 @@ public static byte[] getPassWord(String password) { return null; } byte[] pwd; - pwd = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), password.getBytes()); - pwd = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), pwd); + pwd = Sha256Hash.hash(password.getBytes()); + pwd = Sha256Hash.hash(pwd); pwd = Arrays.copyOfRange(pwd, 0, 16); return pwd; } @@ -491,8 +489,7 @@ public static byte[] getEncKey(String password) { return null; } byte[] encKey; - encKey = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), password.getBytes()); + encKey = Sha256Hash.hash(password.getBytes()); encKey = Arrays.copyOfRange(encKey, 0, 16); return encKey; } @@ -558,10 +555,8 @@ public static boolean addressValid(byte[] address) { */ public static String encode58Check(byte[] input) { - byte[] hash0 = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), input); - byte[] hash1 = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), hash0); + byte[] hash0 = Sha256Hash.hash(input); + byte[] hash1 = Sha256Hash.hash(hash0); byte[] inputCheck = new byte[input.length + 4]; System.arraycopy(input, 0, inputCheck, 0, input.length); System.arraycopy(hash1, 0, inputCheck, input.length, 4); @@ -575,10 +570,8 @@ private static byte[] decode58Check(String input) { } byte[] decodeData = new byte[decodeCheck.length - 4]; System.arraycopy(decodeCheck, 0, decodeData, 0, decodeData.length); - byte[] hash0 = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), decodeData); - byte[] hash1 = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), hash0); + byte[] hash0 = Sha256Hash.hash(decodeData); + byte[] hash1 = Sha256Hash.hash(hash0); if (hash1[0] == decodeCheck[decodeData.length] && hash1[1] == decodeCheck[decodeData.length + 1] && hash1[2] == decodeCheck[decodeData.length + 2] diff --git a/framework/src/test/java/org/tron/common/utils/client/utils/Base58.java b/framework/src/test/java/org/tron/common/utils/client/utils/Base58.java index 2106b191af9..74fe54c5731 100644 --- a/framework/src/test/java/org/tron/common/utils/client/utils/Base58.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/Base58.java @@ -212,10 +212,8 @@ public static boolean addressValid(byte[] address) { */ public static String encode58Check(byte[] input) { - byte[] hash0 = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), input); - byte[] hash1 = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), hash0); + byte[] hash0 = Sha256Hash.hash(input); + byte[] hash1 = Sha256Hash.hash(hash0); byte[] inputCheck = new byte[input.length + 4]; System.arraycopy(input, 0, inputCheck, 0, input.length); System.arraycopy(hash1, 0, inputCheck, input.length, 4); @@ -229,8 +227,8 @@ public static byte[] decode58CheckForShield(String input) { } byte[] decodeData = new byte[decodeCheck.length - 4]; System.arraycopy(decodeCheck, 0, decodeData, 0, decodeData.length); - byte[] hash0 = Sha256Sm3Hash.hash(decodeData); - byte[] hash1 = Sha256Sm3Hash.hash(hash0); + byte[] hash0 = Sha256Hash.hash(decodeData); + byte[] hash1 = Sha256Hash.hash(hash0); if (hash1[0] == decodeCheck[decodeData.length] && hash1[1] == decodeCheck[decodeData.length + 1] && hash1[2] == decodeCheck[decodeData.length + 2] diff --git a/framework/src/test/java/org/tron/common/utils/client/utils/Sha256Sm3Hash.java b/framework/src/test/java/org/tron/common/utils/client/utils/Sha256Sm3Hash.java deleted file mode 100644 index a034f9e816a..00000000000 --- a/framework/src/test/java/org/tron/common/utils/client/utils/Sha256Sm3Hash.java +++ /dev/null @@ -1,333 +0,0 @@ -package org.tron.common.utils.client.utils; - -/* - * Copyright 2011 Google Inc. - * Copyright 2014 Andreas Schildbach - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import com.google.common.base.Preconditions; -import com.google.common.io.ByteStreams; -import com.google.common.primitives.Ints; -import com.google.common.primitives.Longs; -import com.google.protobuf.ByteString; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.Serializable; -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Arrays; - -import org.bouncycastle.crypto.digests.SM3Digest; -import org.tron.common.utils.ByteArray; - - -/** - * A Sha256Sm3Hash just wraps a byte[] so that equals and hashcode work correctly, allowing it to be - * used as keys in a map. It also checks that the length is correct and provides a bit more type - * safety. - */ -public class Sha256Sm3Hash implements Serializable, Comparable { - - public static final int LENGTH = 32; // bytes - public static final Sha256Sm3Hash ZERO_HASH = wrap(new byte[LENGTH]); - - private final byte[] bytes; - private static boolean isEckey = true; - - public Sha256Sm3Hash(long num, byte[] hash) { - byte[] rawHashBytes = this.generateBlockId(num, hash); - Preconditions.checkArgument(rawHashBytes.length == LENGTH); - this.bytes = rawHashBytes; - } - - public Sha256Sm3Hash(long num, Sha256Sm3Hash hash) { - byte[] rawHashBytes = this.generateBlockId(num, hash); - Preconditions.checkArgument(rawHashBytes.length == LENGTH); - this.bytes = rawHashBytes; - } - - /** - * Use {@link #wrap(byte[])} instead. - */ - @Deprecated - public Sha256Sm3Hash(byte[] rawHashBytes) { - Preconditions.checkArgument(rawHashBytes.length == LENGTH); - this.bytes = rawHashBytes; - } - - /** - * Creates a new instance that wraps the given hash value. - * - * @param rawHashBytes the raw hash bytes to wrap - * @return a new instance - * @throws IllegalArgumentException if the given array length is not exactly 32 - */ - @SuppressWarnings("deprecation") // the constructor will be made private in the future - public static Sha256Sm3Hash wrap(byte[] rawHashBytes) { - return new Sha256Sm3Hash(rawHashBytes); - } - - public static Sha256Sm3Hash wrap(ByteString rawHashByteString) { - return wrap(rawHashByteString.toByteArray()); - } - - /** - * Use {@link #of(byte[])} instead: this old name is ambiguous. - */ - @Deprecated - public static Sha256Sm3Hash create(byte[] contents) { - return of(contents); - } - - /** - * Creates a new instance containing the calculated (one-time) hash of the given bytes. - * - * @param contents the bytes on which the hash value is calculated - * @return a new instance containing the calculated (one-time) hash - */ - public static Sha256Sm3Hash of(byte[] contents) { - return wrap(hash(contents)); - } - - /** - * Creates a new instance containing the calculated (one-time) hash of the given file's contents. - * The file contents are read fully into memory, so this method should only be used with small - * files. - * - * @param file the file on which the hash value is calculated - * @return a new instance containing the calculated (one-time) hash - * @throws IOException if an error occurs while reading the file - */ - public static Sha256Sm3Hash of(File file) throws IOException { - - try (FileInputStream in = new FileInputStream(file)) { - return of(ByteStreams.toByteArray(in)); - } - } - - /** - * Use {@link #twiceOf(byte[])} instead: this old name is ambiguous. - */ - @Deprecated - public static Sha256Sm3Hash createDouble(byte[] contents) { - return twiceOf(contents); - } - - /** - * Creates a new instance containing the hash of the calculated hash of the given bytes. - * - * @param contents the bytes on which the hash value is calculated - * @return a new instance containing the calculated (two-time) hash - */ - public static Sha256Sm3Hash twiceOf(byte[] contents) { - return wrap(hashTwice(contents)); - } - - /** - * Returns a new SHA-256 MessageDigest instance. This is a convenience method which wraps the - * checked exception that can never occur with a RuntimeException. - * - * @return a new SHA-256 MessageDigest instance - */ - public static MessageDigest newDigest() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); // Can't happen. - } - } - - /** - * Returns a new SM3 MessageDigest instance. This is a convenience method which wraps the checked - * exception that can never occur with a RuntimeException. - * - * @return a new SM3 MessageDigest instance - */ - public static SM3Digest newSM3Digest() { - return new SM3Digest(); - } - - /** - * Calculates the SHA-256 hash of the given bytes. - * - * @param input the bytes to hash - * @return the hash (in big-endian order) - */ - public static byte[] hash(byte[] input) { - return hash(input, 0, input.length); - } - - /** - * Calculates the SHA-256 hash of the given byte range. - * - * @param input the array containing the bytes to hash - * @param offset the offset within the array of the bytes to hash - * @param length the number of bytes to hash - * @return the hash (in big-endian order) - */ - public static byte[] hash(byte[] input, int offset, int length) { - if (isEckey) { - MessageDigest digest = newDigest(); - digest.update(input, offset, length); - return digest.digest(); - } else { - SM3Digest digest = newSM3Digest(); - digest.update(input, offset, length); - byte[] eHash = new byte[digest.getDigestSize()]; - digest.doFinal(eHash, 0); - return eHash; - } - - } - - /** - * Calculates the SHA-256 hash of the given bytes, and then hashes the resulting hash again. - * - * @param input the bytes to hash - * @return the double-hash (in big-endian order) - */ - public static byte[] hashTwice(byte[] input) { - return hashTwice(input, 0, input.length); - } - - /** - * Calculates the SHA-256 hash of the given byte range, and then hashes the resulting hash again. - * - * @param input the array containing the bytes to hash - * @param offset the offset within the array of the bytes to hash - * @param length the number of bytes to hash - * @return the double-hash (in big-endian order) - */ - public static byte[] hashTwice(byte[] input, int offset, int length) { - if (isEckey) { - MessageDigest digest = newDigest(); - digest.update(input, offset, length); - return digest.digest(digest.digest()); - } else { - SM3Digest digest = newSM3Digest(); - digest.update(input, offset, length); - byte[] eHash = new byte[digest.getDigestSize()]; - digest.doFinal(eHash, 0); - digest.reset(); - digest.update(eHash, 0, eHash.length); - digest.doFinal(eHash, 0); - return eHash; - } - - } - - /** - * Calculates the hash of hash on the given byte ranges. This is equivalent to concatenating the - * two ranges and then passing the result to {@link #hashTwice(byte[])}. - */ - public static byte[] hashTwice(byte[] input1, int offset1, int length1, - byte[] input2, int offset2, int length2) { - if (isEckey) { - MessageDigest digest = newDigest(); - digest.update(input1, offset1, length1); - digest.update(input2, offset2, length2); - return digest.digest(digest.digest()); - } else { - SM3Digest digest = newSM3Digest(); - digest.update(input1, offset1, length1); - digest.update(input2, offset2, length2); - byte[] eHash = new byte[digest.getDigestSize()]; - digest.doFinal(eHash, 0); - return eHash; - } - } - - private byte[] generateBlockId(long blockNum, Sha256Sm3Hash blockHash) { - byte[] numBytes = Longs.toByteArray(blockNum); - byte[] hash = new byte[blockHash.getBytes().length]; - System.arraycopy(numBytes, 0, hash, 0, 8); - System.arraycopy(blockHash.getBytes(), 8, hash, 8, blockHash.getBytes().length - 8); - return hash; - } - - private byte[] generateBlockId(long blockNum, byte[] blockHash) { - byte[] numBytes = Longs.toByteArray(blockNum); - byte[] hash = new byte[blockHash.length]; - System.arraycopy(numBytes, 0, hash, 0, 8); - System.arraycopy(blockHash, 8, hash, 8, blockHash.length - 8); - return hash; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || !(o instanceof Sha256Sm3Hash)) { - return false; - } - return Arrays.equals(bytes, ((Sha256Sm3Hash) o).bytes); - } - - @Override - public String toString() { - return ByteArray.toHexString(bytes); - } - - /** - * Returns the last four bytes of the wrapped hash. This should be unique enough to be a suitable - * hash code even for blocks, where the goal is to try and get the first bytes to be zeros (i.e. - * the value as a big integer lower than the target value). - */ - @Override - public int hashCode() { - // Use the last 4 bytes, not the first 4 which are often zeros in Bitcoin. - return Ints - .fromBytes(bytes[LENGTH - 4], bytes[LENGTH - 3], bytes[LENGTH - 2], bytes[LENGTH - 1]); - } - - /** - * Returns the bytes interpreted as a positive integer. - */ - public BigInteger toBigInteger() { - return new BigInteger(1, bytes); - } - - /** - * Returns the internal byte array, without defensively copying. Therefore do NOT modify the - * returned array. - */ - public byte[] getBytes() { - return bytes; - } - - /** - * For pb return ByteString. - */ - public ByteString getByteString() { - return ByteString.copyFrom(bytes); - } - - @Override - public int compareTo(final Sha256Sm3Hash other) { - for (int i = LENGTH - 1; i >= 0; i--) { - final int thisByte = this.bytes[i] & 0xff; - final int otherByte = other.bytes[i] & 0xff; - if (thisByte > otherByte) { - return 1; - } - if (thisByte < otherByte) { - return -1; - } - } - return 0; - } -} diff --git a/framework/src/test/java/org/tron/common/utils/client/utils/TransactionUtils.java b/framework/src/test/java/org/tron/common/utils/client/utils/TransactionUtils.java index 63ffe1b58ff..e662d657e5f 100644 --- a/framework/src/test/java/org/tron/common/utils/client/utils/TransactionUtils.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/TransactionUtils.java @@ -24,7 +24,6 @@ import org.slf4j.LoggerFactory; import org.tron.common.crypto.ECKey; import org.tron.common.crypto.ECKey.ECDSASignature; -import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; import org.tron.common.utils.Sha256Hash; import org.tron.core.capsule.TransactionCapsule; @@ -56,8 +55,7 @@ public class TransactionUtils { public static byte[] getHash(Transaction transaction) { Transaction.Builder tmp = transaction.toBuilder(); //tmp.clearId(); - return Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), tmp.build().toByteArray()); + return Sha256Hash.hash(tmp.build().toByteArray()); } /** @@ -133,8 +131,7 @@ public static boolean validTransaction(Transaction signedTransaction) { assert (signedTransaction.getSignatureCount() == signedTransaction.getRawData().getContractCount()); List listContract = signedTransaction.getRawData().getContractList(); - byte[] hash = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), signedTransaction.getRawData().toByteArray()); + byte[] hash = Sha256Hash.hash(signedTransaction.getRawData().toByteArray()); int count = signedTransaction.getSignatureCount(); if (count == 0) { return false; @@ -163,8 +160,7 @@ public static boolean validTransaction(Transaction signedTransaction) { public static Transaction sign(Transaction transaction, ECKey myKey) { Transaction.Builder transactionBuilderSigned = transaction.toBuilder(); - byte[] hash = Sha256Hash.hash(CommonParameter - .getInstance().isECKeyCryptoEngine(), transaction.getRawData().toByteArray()); + byte[] hash = Sha256Hash.hash(transaction.getRawData().toByteArray()); List listContract = transaction.getRawData().getContractList(); for (int i = 0; i < listContract.size(); i++) { ECDSASignature signature = myKey.sign(hash); diff --git a/framework/src/test/java/org/tron/core/capsule/BlockCapsuleTest.java b/framework/src/test/java/org/tron/core/capsule/BlockCapsuleTest.java index b258fbf99a1..2f21064a842 100644 --- a/framework/src/test/java/org/tron/core/capsule/BlockCapsuleTest.java +++ b/framework/src/test/java/org/tron/core/capsule/BlockCapsuleTest.java @@ -174,7 +174,7 @@ public void testHasWitnessSignature() { localWitnesses = new LocalWitnesses(); localWitnesses.setPrivateKeys(Arrays.asList(privateKey)); - localWitnesses.initWitnessAccountAddress(null, true); + localWitnesses.initWitnessAccountAddress(null); Args.setLocalWitnesses(localWitnesses); Assert.assertFalse(blockCapsule0.hasWitnessSignature()); diff --git a/framework/src/test/java/org/tron/core/capsule/utils/MerkleTreeTest.java b/framework/src/test/java/org/tron/core/capsule/utils/MerkleTreeTest.java index c9fea6bce45..0a86380e581 100644 --- a/framework/src/test/java/org/tron/core/capsule/utils/MerkleTreeTest.java +++ b/framework/src/test/java/org/tron/core/capsule/utils/MerkleTreeTest.java @@ -28,15 +28,13 @@ private static List getHash(int hashNum) { bytes[2] = (byte) ((i >> 8) & 0xFF); bytes[1] = (byte) ((i >> 16) & 0xFF); bytes[0] = (byte) ((i >> 24) & 0xFF); - hashList.add(Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), bytes)); + hashList.add(Sha256Hash.of(bytes)); } return hashList; } private static Sha256Hash computeHash(Sha256Hash leftHash, Sha256Hash rightHash) { - return Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), + return Sha256Hash.of( leftHash.getByteString().concat(rightHash.getByteString()).toByteArray()); } @@ -185,10 +183,10 @@ public void testConcurrent() { Sha256Hash root2 = Sha256Hash.wrap( ByteString.fromHex("4bfc60ea3de4f5d1476f839874df0aba38eec4e524d6fa63f5b19c4bf527eaf3")); List list1 = IntStream.range(0, 10000).mapToObj(i -> - Sha256Hash.of(true, ("byte1-" + i).getBytes(StandardCharsets.UTF_8))) + Sha256Hash.of(("byte1-" + i).getBytes(StandardCharsets.UTF_8))) .collect(Collectors.toList()); List list2 = IntStream.range(0, 10000).mapToObj(i -> - Sha256Hash.of(true, ("byte2-" + i).getBytes(StandardCharsets.UTF_8))) + Sha256Hash.of(("byte2-" + i).getBytes(StandardCharsets.UTF_8))) .collect(Collectors.toList()); Assert.assertEquals(root1, MerkleTree.build(list1).getRoot().getHash()); Assert.assertEquals(root2, MerkleTree.build(list2).getRoot().getHash()); diff --git a/framework/src/test/java/org/tron/core/config/args/ArgsTest.java b/framework/src/test/java/org/tron/core/config/args/ArgsTest.java index 2118140b45b..1d108eedcf6 100644 --- a/framework/src/test/java/org/tron/core/config/args/ArgsTest.java +++ b/framework/src/test/java/org/tron/core/config/args/ArgsTest.java @@ -58,7 +58,7 @@ public void get() { LocalWitnesses localWitnesses = new LocalWitnesses(); localWitnesses.setPrivateKeys(Arrays.asList(privateKey)); - localWitnesses.initWitnessAccountAddress(null, true); + localWitnesses.initWitnessAccountAddress(null); Args.setLocalWitnesses(localWitnesses); String address = ByteArray.toHexString(Args.getLocalWitnesses() .getWitnessAccountAddress()); diff --git a/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java b/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java index 1b30518c7e3..28feadbd1db 100644 --- a/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java +++ b/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java @@ -162,13 +162,13 @@ public void testConstructor() { LocalWitnesses localWitnesses = new LocalWitnesses(PublicMethod.getRandomPrivateKey()); LocalWitnesses localWitnesses1 = new LocalWitnesses(Lists.newArrayList(PublicMethod.getRandomPrivateKey())); - localWitnesses.initWitnessAccountAddress(new byte[0], true); + localWitnesses.initWitnessAccountAddress(new byte[0]); Assert.assertNotNull(localWitnesses1.getPublicKey()); LocalWitnesses localWitnesses2 = new LocalWitnesses(); Assert.assertNull(localWitnesses2.getPrivateKey()); Assert.assertNull(localWitnesses2.getPublicKey()); - localWitnesses2.initWitnessAccountAddress(null, true); + localWitnesses2.initWitnessAccountAddress(null); LocalWitnesses localWitnesses3 = new LocalWitnesses(); Assert.assertNull(localWitnesses3.getWitnessAccountAddress()); } diff --git a/framework/src/test/java/org/tron/core/config/args/WitnessInitializerKeystoreTest.java b/framework/src/test/java/org/tron/core/config/args/WitnessInitializerKeystoreTest.java index 80d8287682b..2ee4331b99b 100644 --- a/framework/src/test/java/org/tron/core/config/args/WitnessInitializerKeystoreTest.java +++ b/framework/src/test/java/org/tron/core/config/args/WitnessInitializerKeystoreTest.java @@ -54,7 +54,7 @@ public static void setUp() throws Exception { "config-test.conf"); SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); expectedPrivateKey = ByteArray.toHexString(keyPair.getPrivateKey()); File dir = new File(System.getProperty("user.dir"), DIR_NAME); @@ -153,7 +153,7 @@ public void testTamperedKeystoreRejectedAtSrLoading() throws Exception { // through the WitnessInitializer path. File dir = new File(System.getProperty("user.dir"), DIR_NAME); SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String pwd = "tamperpwd123"; String generatedName = WalletUtils.generateWalletFile(pwd, keyPair, dir, true); File keystoreFile = new File(dir, generatedName); diff --git a/framework/src/test/java/org/tron/core/config/args/WitnessInitializerTest.java b/framework/src/test/java/org/tron/core/config/args/WitnessInitializerTest.java index e0aa2606473..3ecef5b10c9 100644 --- a/framework/src/test/java/org/tron/core/config/args/WitnessInitializerTest.java +++ b/framework/src/test/java/org/tron/core/config/args/WitnessInitializerTest.java @@ -6,7 +6,6 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; @@ -107,7 +106,7 @@ public void testInitFromKeystore() { byte[] keyBytes = Hex.decode(privateKey); when(signInterface.getPrivateKey()).thenReturn(keyBytes); mockedWallet.when(() -> WalletUtils.loadCredentials( - anyString(), any(File.class), anyBoolean())).thenReturn(credentials); + anyString(), any(File.class))).thenReturn(credentials); mockedByteArray.when(() -> ByteArray.toHexString(any())) .thenReturn(privateKey); mockedByteArray.when(() -> ByteArray.fromHexString(anyString())) diff --git a/framework/src/test/java/org/tron/core/db/BlockGenerate.java b/framework/src/test/java/org/tron/core/db/BlockGenerate.java index 197dd562485..2a8a101865e 100644 --- a/framework/src/test/java/org/tron/core/db/BlockGenerate.java +++ b/framework/src/test/java/org/tron/core/db/BlockGenerate.java @@ -50,8 +50,7 @@ public Block getSignedBlock(ByteString witness, long time, byte[] privateKey) { .build(); ECKey ecKey = ECKey.fromPrivate(privateKey); - ECDSASignature signature = ecKey.sign(Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), raw.toByteArray()).getBytes()); + ECDSASignature signature = ecKey.sign(Sha256Hash.of(raw.toByteArray()).getBytes()); ByteString sign = ByteString.copyFrom(signature.toByteArray()); BlockHeader blockHeader = block.getBlockHeader().toBuilder() diff --git a/framework/src/test/java/org/tron/core/db/KhaosDatabaseTest.java b/framework/src/test/java/org/tron/core/db/KhaosDatabaseTest.java index ba7478cb22d..bd4a71beb73 100644 --- a/framework/src/test/java/org/tron/core/db/KhaosDatabaseTest.java +++ b/framework/src/test/java/org/tron/core/db/KhaosDatabaseTest.java @@ -132,26 +132,14 @@ public void testGetBranch() { khaosDatabase.push(block1OnforkB); // case: block num of param1 > block num of param2 Pair result1 = khaosDatabase.getBranch( - Sha256Hash.of( - CommonParameter - .getInstance().isECKeyCryptoEngine(), - block2OnforkA.getInstance().getBlockHeader().getRawData().toByteArray()), - Sha256Hash.of( - CommonParameter - .getInstance().isECKeyCryptoEngine(), - block1OnforkB.getInstance().getBlockHeader().getRawData().toByteArray())); + Sha256Hash.of(block2OnforkA.getInstance().getBlockHeader().getRawData().toByteArray()), + Sha256Hash.of(block1OnforkB.getInstance().getBlockHeader().getRawData().toByteArray())); Assert.assertEquals(forkA, result1.getKey()); Assert.assertEquals(forkB, result1.getValue()); // case: block num of param2 > block num of param1 Pair result2 = khaosDatabase.getBranch( - Sha256Hash.of( - CommonParameter - .getInstance().isECKeyCryptoEngine(), - block1OnforkB.getInstance().getBlockHeader().getRawData().toByteArray()), - Sha256Hash.of( - CommonParameter - .getInstance().isECKeyCryptoEngine(), - block2OnforkA.getInstance().getBlockHeader().getRawData().toByteArray())); + Sha256Hash.of(block1OnforkB.getInstance().getBlockHeader().getRawData().toByteArray()), + Sha256Hash.of(block2OnforkA.getInstance().getBlockHeader().getRawData().toByteArray())); Assert.assertEquals(forkB, result2.getKey()); Assert.assertEquals(forkA, result2.getValue()); } catch (UnLinkedBlockException | BadNumberBlockException | NonCommonBlockException e) { @@ -168,4 +156,4 @@ public void testIsNotEmpty() { khaosDatabase.start(blockCapsule); khaosDatabase.isNotEmpty(); } -} \ No newline at end of file +} 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 958a132fbbf..f85ba469b34 100755 --- a/framework/src/test/java/org/tron/core/db/ManagerTest.java +++ b/framework/src/test/java/org/tron/core/db/ManagerTest.java @@ -147,7 +147,7 @@ protected void afterInit() { localWitnesses = new LocalWitnesses(); localWitnesses.setPrivateKeys(Arrays.asList(privateKey)); - localWitnesses.initWitnessAccountAddress(null, true); + localWitnesses.initWitnessAccountAddress(null); Args.setLocalWitnesses(localWitnesses); blockCapsule2 = diff --git a/framework/src/test/java/org/tron/core/db/TransactionExpireTest.java b/framework/src/test/java/org/tron/core/db/TransactionExpireTest.java index e107979107a..0bcf646a966 100644 --- a/framework/src/test/java/org/tron/core/db/TransactionExpireTest.java +++ b/framework/src/test/java/org/tron/core/db/TransactionExpireTest.java @@ -45,7 +45,7 @@ private void initLocalWitness() { String randomPrivateKey = PublicMethod.getRandomPrivateKey(); LocalWitnesses localWitnesses = new LocalWitnesses(); localWitnesses.setPrivateKeys(Arrays.asList(randomPrivateKey)); - localWitnesses.initWitnessAccountAddress(null, true); + localWitnesses.initWitnessAccountAddress(null); Args.setLocalWitnesses(localWitnesses); } diff --git a/framework/src/test/java/org/tron/core/db2/CheckpointV2Test.java b/framework/src/test/java/org/tron/core/db2/CheckpointV2Test.java index 61fc8b61724..495014653b3 100644 --- a/framework/src/test/java/org/tron/core/db2/CheckpointV2Test.java +++ b/framework/src/test/java/org/tron/core/db2/CheckpointV2Test.java @@ -72,7 +72,7 @@ public void testCheckpointV2() { while (iterator.hasNext()) { Map.Entry entry = iterator.next(); byte[] hashBytes = Bytes.concat(entry.getKey(), entry.getValue()); - preDbHash = Sha256Hash.of(true, Bytes.concat(preDbHash.getBytes(), hashBytes)); + preDbHash = Sha256Hash.of(Bytes.concat(preDbHash.getBytes(), hashBytes)); } revokingDatabase.check(); @@ -83,7 +83,7 @@ public void testCheckpointV2() { while (iterator2.hasNext()) { Map.Entry entry = iterator2.next(); byte[] hashBytes = Bytes.concat(entry.getKey(), entry.getValue()); - afterDbHash = Sha256Hash.of(true, Bytes.concat(afterDbHash.getBytes(), hashBytes)); + afterDbHash = Sha256Hash.of(Bytes.concat(afterDbHash.getBytes(), hashBytes)); } Assert.assertEquals(0, preDbHash.compareTo(afterDbHash)); diff --git a/framework/src/test/java/org/tron/core/net/messagehandler/PbftMsgHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/PbftMsgHandlerTest.java index 15d7107b58f..a6e41756328 100644 --- a/framework/src/test/java/org/tron/core/net/messagehandler/PbftMsgHandlerTest.java +++ b/framework/src/test/java/org/tron/core/net/messagehandler/PbftMsgHandlerTest.java @@ -94,10 +94,9 @@ public void testPbft() throws Exception { .setData(blockCapsule.getBlockId().getByteString()); Protocol.PBFTMessage.Raw raw = rawBuilder.build(); builder.setRawData(raw); - SignInterface sign = SignUtils.fromPrivate(Hex.decode(PublicMethod.getRandomPrivateKey()), - true); + SignInterface sign = SignUtils.fromPrivate(Hex.decode(PublicMethod.getRandomPrivateKey())); builder.setSignature(ByteString.copyFrom(sign.Base64toBytes(sign.signHash( - Sha256Hash.hash(true, raw.toByteArray()))))); + Sha256Hash.hash(raw.toByteArray()))))); Protocol.PBFTMessage message = builder.build(); pbftMessage.setType(MessageTypes.PBFT_MSG.asByte()); pbftMessage.setPbftMessage(message); diff --git a/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java b/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java index 7c28757bd5c..51b698250d3 100644 --- a/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java +++ b/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java @@ -177,14 +177,11 @@ private void testCheckHelloMessage() { Node node = new Node(NetUtil.getNodeId(), a1.getAddress().getHostAddress(), null, a1.getPort()); - SignInterface cryptoEngine = SignUtils.fromPrivate(ByteArray.fromHexString(key), - Args.getInstance().isECKeyCryptoEngine()); + SignInterface cryptoEngine = SignUtils.fromPrivate(ByteArray.fromHexString(key)); HelloMessage helloMessage = new HelloMessage(node, System.currentTimeMillis(), ChainBaseManager.getChainBaseManager()); ByteString sig = ByteString.copyFrom(cryptoEngine.Base64toBytes(cryptoEngine - .signHash(Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), ByteArray.fromLong(helloMessage - .getTimestamp())).getBytes()))); + .signHash(Sha256Hash.of(ByteArray.fromLong(helloMessage.getTimestamp())).getBytes()))); helloMessage.setHelloMessage(helloMessage.getHelloMessage().toBuilder() .setAddress(address) .setSignature(sig) diff --git a/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java b/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java index c3ac5800971..6d20f72da19 100644 --- a/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java +++ b/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java @@ -806,8 +806,7 @@ private static BlockIdentifier getBlockIdentifier() { Block nowBlock = blockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); raw rawData = nowBlock.getBlockHeader().getRawData(); BlockCapsule.BlockId blockId = - new BlockCapsule.BlockId(Sha256Hash.of(getInstance().isECKeyCryptoEngine(), - rawData.toByteArray()), + new BlockCapsule.BlockId(Sha256Hash.of(rawData.toByteArray()), rawData.getNumber()); return BlockIdentifier.newBuilder() .setNumber(rawData.getNumber()) diff --git a/framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServletTest.java b/framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServletTest.java index cacb904d9b9..9381e4b199b 100644 --- a/framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServletTest.java +++ b/framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServletTest.java @@ -114,8 +114,8 @@ public void successfulLookupKeepsTransaction() throws Exception { assertEquals(0, rawData.getJSONArray("contract").size()); assertEquals(ByteArray.toHexString(transaction.getRawData().toByteArray()), body.getString("raw_data_hex")); - assertEquals(Sha256Hash.of(Args.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()).toString(), body.getString("txID")); + assertEquals(Sha256Hash.of(transaction.getRawData().toByteArray()).toString(), + body.getString("txID")); assertEquals(1, body.getJSONArray("signature").size()); assertEquals(ByteArray.toHexString(signature.toByteArray()), body.getJSONArray("signature").getString(0)); diff --git a/framework/src/test/java/org/tron/core/zksnark/MerkleContainerTest.java b/framework/src/test/java/org/tron/core/zksnark/MerkleContainerTest.java index 61fb36a9f68..7cfa4a75c4d 100644 --- a/framework/src/test/java/org/tron/core/zksnark/MerkleContainerTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/MerkleContainerTest.java @@ -212,8 +212,7 @@ private void initMerkleTreeWitnessInfo() throws ZksnarkException { Transaction transaction2 = createTransaction(cm3, cm4); Block block = Block.newBuilder().addTransactions(0, transaction) .addTransactions(1, transaction2).build(); - Sha256Hash blockKey = Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), ByteArray.fromLong(blockNum)); + Sha256Hash blockKey = Sha256Hash.of(ByteArray.fromLong(blockNum)); BlockId blockId = new BlockId(blockKey, blockNum); dbManager.getBlockStore().put(blockId.getBytes(), new BlockCapsule(block)); dbManager.getBlockIndexStore().put(blockId); @@ -252,8 +251,7 @@ private void initMerkleTreeWitnessInfo() throws ZksnarkException { String cm2 = "2e0bfc1e123edcb6252251611650f3667371f781b60302385c414716c75e8abc"; Transaction transaction = createTransaction(cm1, cm2); Block block = Block.newBuilder().addTransactions(0, transaction).build(); - Sha256Hash blockKey = Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), ByteArray.fromLong(blockNum)); + Sha256Hash blockKey = Sha256Hash.of(ByteArray.fromLong(blockNum)); BlockId blockId = new BlockId(blockKey, blockNum); dbManager.getBlockStore().put(blockId.getBytes(), new BlockCapsule(block)); dbManager.getBlockIndexStore().put(blockId); @@ -282,8 +280,7 @@ private void initMerkleTreeWitnessInfo() throws ZksnarkException { Transaction transaction2 = createTransaction(cm3, cm4); Block block = Block.newBuilder().addTransactions(0, transaction) .addTransactions(1, transaction2).build(); - Sha256Hash blockKey = Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), ByteArray.fromLong(blockNum)); + Sha256Hash blockKey = Sha256Hash.of(ByteArray.fromLong(blockNum)); BlockId blockId = new BlockId(blockKey, blockNum); dbManager.getBlockStore().put(blockId.getBytes(), new BlockCapsule(block)); dbManager.getBlockIndexStore().put(blockId); @@ -323,8 +320,7 @@ private void initMerkleTreeWitnessInfo() throws ZksnarkException { String cm2 = "26e8c4061f2ad984d19f2c0a4436b9800e529069c0b0d3186d4683e83bb7eb8c"; Transaction transaction = createTransaction(cm1, cm2); Block block = Block.newBuilder().addTransactions(0, transaction).build(); - Sha256Hash blockKey = Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), ByteArray.fromLong(blockNum)); + Sha256Hash blockKey = Sha256Hash.of(ByteArray.fromLong(blockNum)); BlockId blockId = new BlockId(blockKey, blockNum); dbManager.getBlockStore().put(blockId.getBytes(), new BlockCapsule(block)); dbManager.getBlockIndexStore().put(blockId); diff --git a/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java b/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java index efa60139b12..7af3be0b2e1 100644 --- a/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java @@ -640,8 +640,7 @@ public void pushShieldedTransactionAndDecryptWithOvk() } private byte[] getHash() { - return Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), "this is a test".getBytes()).getBytes(); + return Sha256Hash.of("this is a test".getBytes()).getBytes(); } @Ignore diff --git a/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java b/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java index e62396bc046..d66a14efeeb 100755 --- a/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java @@ -1669,13 +1669,9 @@ private byte[] hashWithMissingColumn(TransactionCapsule tx, TestSignMissingColum .setRawData(rawBuilder).build(); byte[] mergedByte = Bytes.concat( - Sha256Hash.of( - CommonParameter - .getInstance().isECKeyCryptoEngine(), - CommonParameter.getInstance().getZenTokenId().getBytes()).getBytes(), + Sha256Hash.of(CommonParameter.getInstance().getZenTokenId().getBytes()).getBytes(), transaction.getRawData().toByteArray()); - return Sha256Hash.of(CommonParameter - .getInstance().isECKeyCryptoEngine(), mergedByte).getBytes(); + return Sha256Hash.of(mergedByte).getBytes(); } private ZenTransactionBuilder generateShield2ShieldBuilder(ZenTransactionBuilder builder, diff --git a/framework/src/test/java/org/tron/keystore/CredentialsTest.java b/framework/src/test/java/org/tron/keystore/CredentialsTest.java index a072253ff58..ee7bc0ac0e4 100644 --- a/framework/src/test/java/org/tron/keystore/CredentialsTest.java +++ b/framework/src/test/java/org/tron/keystore/CredentialsTest.java @@ -4,7 +4,6 @@ import org.junit.Test; import org.mockito.Mockito; import org.tron.common.crypto.SignInterface; -import org.tron.common.crypto.sm2.SM2; import org.tron.common.utils.ByteUtil; import org.tron.common.utils.StringUtil; @@ -31,15 +30,6 @@ public void testCreate() { credentials.getSignInterface()); } - @Test - public void testCreateFromSM2() { - Exception e = Assert.assertThrows(Exception.class, - () -> Credentials.create(SM2.fromNodeId(ByteUtil.hexToBytes("fffffffffff" - + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - + "fffffffffffffffffffffffffffffffffffffff")))); - Assert.assertTrue(e instanceof IllegalArgumentException); - } - @Test public void testEquals() { Credentials credentials1 = Credentials.create(mockSignInterface(ADDRESS_1)); diff --git a/framework/src/test/java/org/tron/keystore/CrossImplTest.java b/framework/src/test/java/org/tron/keystore/CrossImplTest.java index 6b00c57c1f9..589180bf121 100644 --- a/framework/src/test/java/org/tron/keystore/CrossImplTest.java +++ b/framework/src/test/java/org/tron/keystore/CrossImplTest.java @@ -61,7 +61,7 @@ public class CrossImplTest { @Test public void testDecryptEthPbkdf2Keystore() throws Exception { WalletFile walletFile = MAPPER.readValue(ETH_PBKDF2_KEYSTORE, WalletFile.class); - SignInterface recovered = Wallet.decrypt(ETH_PASSWORD, walletFile, true); + SignInterface recovered = Wallet.decrypt(ETH_PASSWORD, walletFile); assertEquals("Private key must match Ethereum test vector", ETH_PRIVATE_KEY, org.tron.common.utils.ByteArray.toHexString(recovered.getPrivateKey())); @@ -70,7 +70,7 @@ public void testDecryptEthPbkdf2Keystore() throws Exception { @Test public void testDecryptEthScryptKeystore() throws Exception { WalletFile walletFile = MAPPER.readValue(ETH_SCRYPT_KEYSTORE, WalletFile.class); - SignInterface recovered = Wallet.decrypt(ETH_PASSWORD, walletFile, true); + SignInterface recovered = Wallet.decrypt(ETH_PASSWORD, walletFile); assertEquals("Private key must match Ethereum test vector", ETH_PRIVATE_KEY, org.tron.common.utils.ByteArray.toHexString(recovered.getPrivateKey())); @@ -80,7 +80,7 @@ public void testDecryptEthScryptKeystore() throws Exception { @Test public void testKeystoreFormatCompatibility() throws Exception { - SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom(), true); + SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom()); byte[] originalKey = keyPair.getPrivateKey(); String password = "dynamicTest123"; @@ -101,7 +101,7 @@ public void testKeystoreFormatCompatibility() throws Exception { MAPPER.writeValue(tempFile, walletFile); WalletFile loaded = MAPPER.readValue(tempFile, WalletFile.class); - SignInterface recovered = Wallet.decrypt(password, loaded, true); + SignInterface recovered = Wallet.decrypt(password, loaded); assertArrayEquals("Key must survive file roundtrip", originalKey, recovered.getPrivateKey()); @@ -113,7 +113,7 @@ public void testKeystoreFormatCompatibility() throws Exception { @Test public void testLightScryptFormatCompatibility() throws Exception { - SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom(), true); + SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom()); byte[] originalKey = keyPair.getPrivateKey(); String password = "lightCompat456"; @@ -122,7 +122,7 @@ public void testLightScryptFormatCompatibility() throws Exception { MAPPER.writeValue(tempFile, walletFile); WalletFile loaded = MAPPER.readValue(tempFile, WalletFile.class); - SignInterface recovered = Wallet.decrypt(password, loaded, true); + SignInterface recovered = Wallet.decrypt(password, loaded); assertArrayEquals("Key must survive light scrypt file roundtrip", originalKey, recovered.getPrivateKey()); } @@ -130,14 +130,14 @@ public void testLightScryptFormatCompatibility() throws Exception { @Test public void testKeystoreAddressConsistency() throws Exception { String password = "addresscheck"; - SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom(), true); + SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom()); Credentials original = Credentials.create(keyPair); WalletFile walletFile = Wallet.createLight(password, keyPair); assertEquals("WalletFile address must match credentials address", original.getAddress(), walletFile.getAddress()); - SignInterface recovered = Wallet.decrypt(password, walletFile, true); + SignInterface recovered = Wallet.decrypt(password, walletFile); Credentials recoveredCreds = Credentials.create(recovered); assertEquals("Recovered address must match original", original.getAddress(), recoveredCreds.getAddress()); @@ -146,7 +146,7 @@ public void testKeystoreAddressConsistency() throws Exception { @Test public void testLoadCredentialsIntegration() throws Exception { String password = "integration789"; - SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom(), true); + SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom()); byte[] originalKey = keyPair.getPrivateKey(); String originalAddress = Credentials.create(keyPair).getAddress(); @@ -155,7 +155,7 @@ public void testLoadCredentialsIntegration() throws Exception { assertNotNull(fileName); File keystoreFile = new File(tempDir, fileName); - Credentials loaded = WalletUtils.loadCredentials(password, keystoreFile, true); + Credentials loaded = WalletUtils.loadCredentials(password, keystoreFile); assertEquals("Address must survive full WalletUtils roundtrip", originalAddress, loaded.getAddress()); diff --git a/framework/src/test/java/org/tron/keystore/WalletAddressValidationTest.java b/framework/src/test/java/org/tron/keystore/WalletAddressValidationTest.java index 82008988b6e..52a828c8b31 100644 --- a/framework/src/test/java/org/tron/keystore/WalletAddressValidationTest.java +++ b/framework/src/test/java/org/tron/keystore/WalletAddressValidationTest.java @@ -21,11 +21,11 @@ public class WalletAddressValidationTest { @Test public void testDecryptAcceptsMatchingAddress() throws Exception { String password = "test123456"; - SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom(), true); + SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom()); WalletFile walletFile = Wallet.createStandard(password, keyPair); // createStandard sets the correct derived address — should decrypt fine - SignInterface recovered = Wallet.decrypt(password, walletFile, true); + SignInterface recovered = Wallet.decrypt(password, walletFile); assertEquals("Private key must match", org.tron.common.utils.ByteArray.toHexString(keyPair.getPrivateKey()), org.tron.common.utils.ByteArray.toHexString(recovered.getPrivateKey())); @@ -34,14 +34,14 @@ public void testDecryptAcceptsMatchingAddress() throws Exception { @Test public void testDecryptRejectsSpoofedAddress() throws Exception { String password = "test123456"; - SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom(), true); + SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom()); WalletFile walletFile = Wallet.createStandard(password, keyPair); // Tamper with the address to simulate a spoofed keystore walletFile.setAddress("TTamperedAddressXXXXXXXXXXXXXXXXXX"); try { - Wallet.decrypt(password, walletFile, true); + Wallet.decrypt(password, walletFile); fail("Expected CipherException due to address mismatch"); } catch (CipherException e) { assertTrue("Error should mention address mismatch, got: " + e.getMessage(), @@ -53,11 +53,11 @@ public void testDecryptRejectsSpoofedAddress() throws Exception { public void testDecryptAllowsNullAddress() throws Exception { // Ethereum-style keystores may not include the address field — should still decrypt String password = "test123456"; - SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom(), true); + SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom()); WalletFile walletFile = Wallet.createStandard(password, keyPair); walletFile.setAddress(null); - SignInterface recovered = Wallet.decrypt(password, walletFile, true); + SignInterface recovered = Wallet.decrypt(password, walletFile); assertNotNull(recovered); assertEquals(org.tron.common.utils.ByteArray.toHexString(keyPair.getPrivateKey()), org.tron.common.utils.ByteArray.toHexString(recovered.getPrivateKey())); @@ -66,28 +66,13 @@ public void testDecryptAllowsNullAddress() throws Exception { @Test public void testDecryptAllowsEmptyAddress() throws Exception { String password = "test123456"; - SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom(), true); + SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom()); WalletFile walletFile = Wallet.createStandard(password, keyPair); walletFile.setAddress(""); // Empty-string address is treated as absent (no validation) - SignInterface recovered = Wallet.decrypt(password, walletFile, true); + SignInterface recovered = Wallet.decrypt(password, walletFile); assertNotNull(recovered); } - @Test - public void testDecryptRejectsSpoofedAddressSm2() throws Exception { - String password = "test123456"; - SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom(), false); - WalletFile walletFile = Wallet.createStandard(password, keyPair); - - walletFile.setAddress("TSpoofedSm2Addr123456789XXXXXXXX"); - - try { - Wallet.decrypt(password, walletFile, false); - fail("Expected CipherException due to address mismatch on SM2"); - } catch (CipherException e) { - assertTrue(e.getMessage().contains("address mismatch")); - } - } } diff --git a/framework/src/test/java/org/tron/keystore/WalletFileTest.java b/framework/src/test/java/org/tron/keystore/WalletFileTest.java index c24647be322..272a29e6838 100644 --- a/framework/src/test/java/org/tron/keystore/WalletFileTest.java +++ b/framework/src/test/java/org/tron/keystore/WalletFileTest.java @@ -14,9 +14,9 @@ public class WalletFileTest { @Test public void testGetAddress() throws NoSuchAlgorithmException, CipherException { WalletFile walletFile1 = Wallet.createStandard("", SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"),true)); + SecureRandom.getInstance("NativePRNG"))); WalletFile walletFile2 = Wallet.createStandard("", SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"),true)); + SecureRandom.getInstance("NativePRNG"))); WalletFile walletFile3 = (WalletFile) getSame(walletFile1); Assert.assertNotEquals(walletFile1.getAddress(), walletFile2.getAddress()); Assert.assertNotEquals(walletFile1.getCrypto(), walletFile2.getCrypto()); diff --git a/framework/src/test/java/org/tron/keystore/WalletPropertyTest.java b/framework/src/test/java/org/tron/keystore/WalletPropertyTest.java index 3028d2a7799..a13c766ca87 100644 --- a/framework/src/test/java/org/tron/keystore/WalletPropertyTest.java +++ b/framework/src/test/java/org/tron/keystore/WalletPropertyTest.java @@ -23,11 +23,11 @@ public class WalletPropertyTest { public void encryptDecryptRoundtripLight() throws Exception { for (int i = 0; i < 100; i++) { String password = randomPassword(6, 32); - SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom(), true); + SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom()); byte[] originalKey = keyPair.getPrivateKey(); WalletFile walletFile = Wallet.createLight(password, keyPair); - SignInterface recovered = Wallet.decrypt(password, walletFile, true); + SignInterface recovered = Wallet.decrypt(password, walletFile); assertArrayEquals("Roundtrip failed at iteration " + i, originalKey, recovered.getPrivateKey()); @@ -39,11 +39,11 @@ public void encryptDecryptRoundtripStandard() throws Exception { // Fewer iterations for standard scrypt (slow, ~10s each) for (int i = 0; i < 2; i++) { String password = randomPassword(6, 16); - SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom(), true); + SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom()); byte[] originalKey = keyPair.getPrivateKey(); WalletFile walletFile = Wallet.createStandard(password, keyPair); - SignInterface recovered = Wallet.decrypt(password, walletFile, true); + SignInterface recovered = Wallet.decrypt(password, walletFile); assertArrayEquals("Standard roundtrip failed at iteration " + i, originalKey, recovered.getPrivateKey()); @@ -54,11 +54,11 @@ public void encryptDecryptRoundtripStandard() throws Exception { public void wrongPasswordFailsDecrypt() throws Exception { for (int i = 0; i < 50; i++) { String password = randomPassword(6, 16); - SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom(), true); + SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom()); WalletFile walletFile = Wallet.createLight(password, keyPair); try { - Wallet.decrypt(password + "X", walletFile, true); + Wallet.decrypt(password + "X", walletFile); throw new AssertionError("Expected CipherException at iteration " + i); } catch (CipherException e) { // Expected diff --git a/framework/src/test/java/org/tron/keystore/WalletUtilsWriteTest.java b/framework/src/test/java/org/tron/keystore/WalletUtilsWriteTest.java index a7472149658..28463a8000a 100644 --- a/framework/src/test/java/org/tron/keystore/WalletUtilsWriteTest.java +++ b/framework/src/test/java/org/tron/keystore/WalletUtilsWriteTest.java @@ -35,7 +35,7 @@ public class WalletUtilsWriteTest { public TemporaryFolder tempFolder = new TemporaryFolder(); private static WalletFile lightWalletFile(String password) throws Exception { - SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom(), true); + SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom()); return Wallet.createLight(password, keyPair); } @@ -45,7 +45,7 @@ public void testGenerateWalletFileCreatesOwnerOnlyFile() throws Exception { !System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win")); File dir = tempFolder.newFolder("gen-perms"); - SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom(), true); + SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom()); String fileName = WalletUtils.generateWalletFile("password123", keyPair, dir, false); @@ -61,7 +61,7 @@ public void testGenerateWalletFileCreatesOwnerOnlyFile() throws Exception { @Test public void testGenerateWalletFileLeavesNoTempFile() throws Exception { File dir = tempFolder.newFolder("gen-no-temp"); - SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom(), true); + SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom()); WalletUtils.generateWalletFile("password123", keyPair, dir, false); @@ -74,7 +74,7 @@ public void testGenerateWalletFileLeavesNoTempFile() throws Exception { @Test public void testGenerateWalletFileLightScrypt() throws Exception { File dir = tempFolder.newFolder("gen-light"); - SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom(), true); + SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom()); String fileName = WalletUtils.generateWalletFile("password123", keyPair, dir, false); assertNotNull(fileName); @@ -176,7 +176,7 @@ public void testLoadCredentialsFollowsSymlinkButWarns() throws Exception { !System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win")); File realDir = tempFolder.newFolder("load-symlink-target"); - SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom(), true); + SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom()); String realName = WalletUtils.generateWalletFile("password123", keyPair, realDir, false); File realKeystore = new File(realDir, realName); @@ -188,18 +188,18 @@ public void testLoadCredentialsFollowsSymlinkButWarns() throws Exception { // for the operator. Hard-rejecting would silently break legitimate SR // deployments that organize keystores via symlinks. Credentials creds = - WalletUtils.loadCredentials("password123", symlink, true); + WalletUtils.loadCredentials("password123", symlink); assertNotNull(creds.getAddress()); } @Test public void testLoadCredentialsAcceptsRegularFile() throws Exception { File dir = tempFolder.newFolder("load-ok"); - SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom(), true); + SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom()); String fileName = WalletUtils.generateWalletFile("password123", keyPair, dir, false); Credentials creds = - WalletUtils.loadCredentials("password123", new File(dir, fileName), true); + WalletUtils.loadCredentials("password123", new File(dir, fileName)); assertNotNull(creds.getAddress()); } } diff --git a/framework/src/test/java/org/tron/program/FullNodeCryptoEngineTest.java b/framework/src/test/java/org/tron/program/FullNodeCryptoEngineTest.java new file mode 100644 index 00000000000..dfa77bb715b --- /dev/null +++ b/framework/src/test/java/org/tron/program/FullNodeCryptoEngineTest.java @@ -0,0 +1,123 @@ +package org.tron.program; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; + +import com.typesafe.config.ConfigUtil; +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.tron.common.application.Application; +import org.tron.common.application.ApplicationFactory; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.exit.ExitManager; +import org.tron.common.log.LogService; +import org.tron.common.prometheus.Metrics; +import org.tron.core.config.args.Args; +import org.tron.core.config.args.WitnessInitializer; + +public class FullNodeCryptoEngineTest { + + @Rule + public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Before + public void setUp() { + Args.clearParam(); + } + + @After + public void tearDown() { + Args.clearParam(); + } + + @Test + public void testStartupWithoutCryptoEngine() throws Exception { + assertStartup(""); + } + + @Test + public void testStartupWithEckey() throws Exception { + assertStartup("crypto.engine = eckey\n"); + } + + @Test + public void testUnsupportedEngineBeforeDatabaseAndKeystore() throws Exception { + for (String engine : new String[]{"sm2", "unknown", "null", "\"\"", "false"}) { + File storage = new File(temporaryFolder.newFolder(), "legacy-database"); + File config = writeConfig("crypto.engine = " + engine + "\n" + + "localwitness = []\nlocalwitnesskeystore = [\"legacy-sm2.json\"]\n" + + "storage.properties = [{ name = account, path = " + + ConfigUtil.quoteString(storage.toString()) + " }]\n"); + File output = new File(temporaryFolder.newFolder(), "chain"); + try (MockedStatic exit = mockStatic(ExitManager.class); + MockedStatic witness = mockStatic(WitnessInitializer.class); + MockedStatic keystore = mockStatic(KeystoreFactory.class); + MockedConstruction contexts = + mockConstruction(TronApplicationContext.class)) { + IllegalArgumentException exception = assertThrows(engine, IllegalArgumentException.class, + () -> FullNode.main(new String[]{"-c", config.toString(), "-d", output.toString(), + "-w", "--password", "test-password"})); + assertTrue(exception.getMessage().contains("SM2/SM3 support has been removed")); + assertTrue(contexts.constructed().isEmpty()); + witness.verifyNoInteractions(); + keystore.verifyNoInteractions(); + assertNull(Args.getStorageConfig()); + assertFalse(storage.exists()); + assertFalse(output.exists()); + + // The legacy keystore-factory entry point must reject the same configuration. + Args.clearParam(); + IllegalArgumentException keystoreException = assertThrows(IllegalArgumentException.class, + () -> FullNode.main(new String[]{"-c", config.toString(), "--keystore-factory"})); + assertTrue(keystoreException.getMessage().contains("SM2/SM3 support has been removed")); + keystore.verifyNoInteractions(); + assertTrue(contexts.constructed().isEmpty()); + assertFalse(storage.exists()); + } + Args.clearParam(); + } + } + + private void assertStartup(String cryptoConfig) throws Exception { + File config = writeConfig(cryptoConfig); + File output = new File(temporaryFolder.newFolder(), "chain"); + Application application = mock(Application.class); + // Exercise the real entry point and config loader, while isolating services and chain stores. + try (MockedStatic exit = mockStatic(ExitManager.class); + MockedStatic logs = mockStatic(LogService.class); + MockedStatic metrics = mockStatic(Metrics.class); + MockedStatic factory = mockStatic(ApplicationFactory.class); + MockedConstruction contexts = + mockConstruction(TronApplicationContext.class)) { + factory.when(() -> ApplicationFactory.create(any())).thenReturn(application); + FullNode.main(new String[]{"-c", config.toString(), "-d", output.toString()}); + assertEquals(1, contexts.constructed().size()); + verify(contexts.constructed().get(0)).refresh(); + verify(application).startup(); + verify(application).blockUntilShutdown(); + } + } + + private File writeConfig(String cryptoConfig) throws Exception { + File config = temporaryFolder.newFile(); + String contents = "include \"config-test.conf\"\n" + cryptoConfig; + Files.write(config.toPath(), contents.getBytes(StandardCharsets.UTF_8)); + return config; + } +} diff --git a/plugins/README.md b/plugins/README.md index f14e070c01a..924526b735b 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -166,7 +166,7 @@ Generate a new keystore file with a random keypair. ```shell script # full command - java -jar Toolkit.jar keystore new [-h] [--keystore-dir=] [--password-file=] [--sm2] [--json] + java -jar Toolkit.jar keystore new [-h] [--keystore-dir=] [--password-file=] [--json] # examples java -jar Toolkit.jar keystore new # interactive prompt java -jar Toolkit.jar keystore new --keystore-dir /data/keystores # custom directory @@ -179,7 +179,7 @@ Import a private key into a new keystore file. ```shell script # full command - java -jar Toolkit.jar keystore import [-h] [--keystore-dir=] [--password-file=] [--key-file=] [--sm2] [--force] [--json] + java -jar Toolkit.jar keystore import [-h] [--keystore-dir=] [--password-file=] [--key-file=] [--force] [--json] # examples java -jar Toolkit.jar keystore import # interactive prompt java -jar Toolkit.jar keystore import --key-file key.txt --json # from file with JSON output @@ -205,7 +205,7 @@ Change the password of a keystore file. ```shell script # full command - java -jar Toolkit.jar keystore update [-h]
[--keystore-dir=] [--password-file=] [--sm2] [--json] + java -jar Toolkit.jar keystore update [-h]
[--keystore-dir=] [--password-file=] [--json] # examples java -jar Toolkit.jar keystore update TXyz...abc # interactive prompt java -jar Toolkit.jar keystore update TXyz...abc --keystore-dir /data/ks # custom directory @@ -219,6 +219,5 @@ When using `--password-file` with `update`, the file must contain exactly two li - `--password-file`: Read password from a file instead of interactive prompt. For `keystore update`, the file must contain exactly two lines (current password, then new password). - `--key-file`: Read the private key (hex, with or without `0x` prefix) from a file instead of the interactive prompt (`keystore import` only). - `--force`: For `keystore import`, allow importing a private key whose address already has a keystore in the directory (creates an additional file). -- `--sm2`: Use SM2 algorithm instead of ECDSA (for `new` and `import`). - `--json`: Output in JSON format for scripting. - `-h | --help`: Provide the help info. diff --git a/plugins/src/main/java/common/org/tron/plugins/DbRoot.java b/plugins/src/main/java/common/org/tron/plugins/DbRoot.java index 45854bbebdc..307eafaa772 100644 --- a/plugins/src/main/java/common/org/tron/plugins/DbRoot.java +++ b/plugins/src/main/java/common/org/tron/plugins/DbRoot.java @@ -109,8 +109,7 @@ private Ret calcMerkleRoot(String name) { } private Sha256Hash getHash(Map.Entry entry) { - return Sha256Hash.of(true, - Bytes.concat(entry.getKey(), entry.getValue())); + return Sha256Hash.of(Bytes.concat(entry.getKey(), entry.getValue())); } private void printInfo(Ret ret) { diff --git a/plugins/src/main/java/common/org/tron/plugins/KeystoreImport.java b/plugins/src/main/java/common/org/tron/plugins/KeystoreImport.java index 67c8e6bc4c6..7830246c41e 100644 --- a/plugins/src/main/java/common/org/tron/plugins/KeystoreImport.java +++ b/plugins/src/main/java/common/org/tron/plugins/KeystoreImport.java @@ -45,10 +45,6 @@ public class KeystoreImport implements Callable { description = "Read password from file instead of interactive prompt") private File passwordFile; - @Option(names = {"--sm2"}, - description = "Use SM2 algorithm instead of ECDSA") - private boolean sm2; - @Option(names = {"--force"}, description = "Allow import even if address already exists") private boolean force; @@ -81,14 +77,11 @@ public Integer call() { return 1; } - boolean ecKey = !sm2; SignInterface keyPair; try { - keyPair = SignUtils.fromPrivate( - ByteArray.fromHexString(privateKey), ecKey); + keyPair = SignUtils.fromPrivate(ByteArray.fromHexString(privateKey)); } catch (Exception e) { - err.println("Invalid private key: not a valid key" - + " for the selected algorithm."); + err.println("Invalid private key: not a valid ECKey private key."); return 1; } String address = Credentials.create(keyPair).getAddress(); diff --git a/plugins/src/main/java/common/org/tron/plugins/KeystoreNew.java b/plugins/src/main/java/common/org/tron/plugins/KeystoreNew.java index 39d2bdd3502..2e565ba2ade 100644 --- a/plugins/src/main/java/common/org/tron/plugins/KeystoreNew.java +++ b/plugins/src/main/java/common/org/tron/plugins/KeystoreNew.java @@ -35,10 +35,6 @@ public class KeystoreNew implements Callable { description = "Read password from file instead of interactive prompt") private File passwordFile; - @Option(names = {"--sm2"}, - description = "Use SM2 algorithm instead of ECDSA") - private boolean sm2; - @Override public Integer call() { PrintWriter out = spec.commandLine().getOut(); @@ -51,8 +47,7 @@ public Integer call() { return 1; } - boolean ecKey = !sm2; - SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom(), ecKey); + SignInterface keyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom()); String fileName = WalletUtils.generateWalletFile( password, keyPair, keystoreDir, true); diff --git a/plugins/src/main/java/common/org/tron/plugins/KeystoreUpdate.java b/plugins/src/main/java/common/org/tron/plugins/KeystoreUpdate.java index 4ef6cbbd71e..cf4737f4488 100644 --- a/plugins/src/main/java/common/org/tron/plugins/KeystoreUpdate.java +++ b/plugins/src/main/java/common/org/tron/plugins/KeystoreUpdate.java @@ -46,10 +46,6 @@ public class KeystoreUpdate implements Callable { description = "Read old and new passwords from file (one per line)") private File passwordFile; - @Option(names = {"--sm2"}, - description = "Use SM2 algorithm instead of ECDSA") - private boolean sm2; - @Override public Integer call() { PrintWriter out = spec.commandLine().getOut(); @@ -143,7 +139,6 @@ public Integer call() { return 1; } - boolean ecKey = !sm2; // Re-read via NOFOLLOW byte channel to close the TOCTOU window between // findKeystoreByAddress and this read — an attacker with directory // write access could otherwise swap the file for a symlink in between. @@ -153,7 +148,7 @@ public Integer call() { return 1; } WalletFile walletFile = MAPPER.readValue(keystoreBytes, WalletFile.class); - SignInterface keyPair = Wallet.decrypt(oldPassword, walletFile, ecKey); + SignInterface keyPair = Wallet.decrypt(oldPassword, walletFile); // createStandard already sets the correctly-derived address. Do NOT override // with walletFile.getAddress() — that would propagate a potentially spoofed diff --git a/plugins/src/main/java/common/org/tron/plugins/utils/CryptoUitls.java b/plugins/src/main/java/common/org/tron/plugins/utils/CryptoUitls.java deleted file mode 100644 index 6d3e4ccb548..00000000000 --- a/plugins/src/main/java/common/org/tron/plugins/utils/CryptoUitls.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.tron.plugins.utils; - -public class CryptoUitls { - - public static final String ECKey_ENGINE = "ECKey"; -} diff --git a/plugins/src/main/java/common/org/tron/plugins/utils/DBUtils.java b/plugins/src/main/java/common/org/tron/plugins/utils/DBUtils.java index 6eb097cbec5..ca3345ba20a 100644 --- a/plugins/src/main/java/common/org/tron/plugins/utils/DBUtils.java +++ b/plugins/src/main/java/common/org/tron/plugins/utils/DBUtils.java @@ -139,7 +139,6 @@ public static String simpleDecode(byte[] bytes) { } public static Sha256Hash getTransactionId(Protocol.Transaction transaction) { - return Sha256Hash.of(true, - transaction.getRawData().toByteArray()); + return Sha256Hash.of(transaction.getRawData().toByteArray()); } } diff --git a/plugins/src/main/java/common/org/tron/plugins/utils/MerkleRoot.java b/plugins/src/main/java/common/org/tron/plugins/utils/MerkleRoot.java index 055f5dcdee0..b77a2a7e5e8 100644 --- a/plugins/src/main/java/common/org/tron/plugins/utils/MerkleRoot.java +++ b/plugins/src/main/java/common/org/tron/plugins/utils/MerkleRoot.java @@ -56,7 +56,7 @@ private static Leaf createLeaf(Sha256Hash hash) { } private static Sha256Hash computeHash(Sha256Hash leftHash, Sha256Hash rightHash) { - return Sha256Hash.of(true, + return Sha256Hash.of( leftHash.getByteString().concat(rightHash.getByteString()).toByteArray()); } diff --git a/plugins/src/main/java/common/org/tron/plugins/utils/Sha256Hash.java b/plugins/src/main/java/common/org/tron/plugins/utils/Sha256Hash.java index 67e6e64ea79..1f49c5f1124 100644 --- a/plugins/src/main/java/common/org/tron/plugins/utils/Sha256Hash.java +++ b/plugins/src/main/java/common/org/tron/plugins/utils/Sha256Hash.java @@ -29,7 +29,6 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; -import org.bouncycastle.crypto.digests.SM3Digest; /** @@ -71,8 +70,8 @@ public static Sha256Hash wrap(byte[] rawHashBytes) { * @param contents the bytes on which the hash value is calculated * @return a new instance containing the calculated (one-time) hash */ - public static Sha256Hash of(boolean isSha256, byte[] contents) { - return wrap(hash(isSha256, contents)); + public static Sha256Hash of(byte[] contents) { + return wrap(hash(contents)); } /** @@ -84,10 +83,10 @@ public static Sha256Hash of(boolean isSha256, byte[] contents) { * @return a new instance containing the calculated (one-time) hash * @throws IOException if an error occurs while reading the file */ - public static Sha256Hash of(boolean isSha256, File file) throws IOException { + public static Sha256Hash of(File file) throws IOException { try (FileInputStream in = new FileInputStream(file)) { - return of(isSha256, ByteStreams.toByteArray(in)); + return of(ByteStreams.toByteArray(in)); } } @@ -106,24 +105,14 @@ public static MessageDigest newDigest() { } } - /** - * Returns a new SM3 MessageDigest instance. This is a convenience method which wraps the checked - * exception that can never occur with a RuntimeException. - * - * @return a new SM3 MessageDigest instance - */ - public static SM3Digest newSM3Digest() { - return new SM3Digest(); - } - /** * Calculates the SHA-256 hash of the given bytes. * * @param input the bytes to hash * @return the hash (in big-endian order) */ - public static byte[] hash(boolean isSha256, byte[] input) { - return hash(isSha256, input, 0, input.length); + public static byte[] hash(byte[] input) { + return hash(input, 0, input.length); } /** @@ -134,19 +123,10 @@ public static byte[] hash(boolean isSha256, byte[] input) { * @param length the number of bytes to hash * @return the hash (in big-endian order) */ - public static byte[] hash(boolean isSha256, byte[] input, int offset, int length) { - if (isSha256) { - MessageDigest digest = newDigest(); - digest.update(input, offset, length); - return digest.digest(); - } else { - SM3Digest digest = newSM3Digest(); - digest.update(input, offset, length); - byte[] eHash = new byte[digest.getDigestSize()]; - digest.doFinal(eHash, 0); - return eHash; - } - + public static byte[] hash(byte[] input, int offset, int length) { + MessageDigest digest = newDigest(); + digest.update(input, offset, length); + return digest.digest(); } @Override diff --git a/plugins/src/test/java/org/tron/plugins/KeystoreImportTest.java b/plugins/src/test/java/org/tron/plugins/KeystoreImportTest.java index 577889fe196..cbb3484d260 100644 --- a/plugins/src/test/java/org/tron/plugins/KeystoreImportTest.java +++ b/plugins/src/test/java/org/tron/plugins/KeystoreImportTest.java @@ -31,7 +31,7 @@ public void testImportWithKeyFileAndPasswordFile() throws Exception { // Generate a known private key SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String privateKeyHex = ByteArray.toHexString(keyPair.getPrivateKey()); String expectedAddress = Credentials.create(keyPair).getAddress(); @@ -54,7 +54,7 @@ public void testImportWithKeyFileAndPasswordFile() throws Exception { assertEquals(1, files.length); // Verify roundtrip: decrypt should recover the same private key - Credentials creds = WalletUtils.loadCredentials("test123456", files[0], true); + Credentials creds = WalletUtils.loadCredentials("test123456", files[0]); assertEquals("Address must match", expectedAddress, creds.getAddress()); assertArrayEquals("Private key must survive import roundtrip", keyPair.getPrivateKey(), creds.getSignInterface().getPrivateKey()); @@ -113,42 +113,11 @@ public void testImportNoTtyNoKeyFile() throws Exception { assertEquals("Should fail when no TTY and no --key-file", 1, exitCode); } - @Test - public void testImportWithSm2() throws Exception { - File dir = tempFolder.newFolder("keystore-sm2"); - // SM2 uses same 32-byte private key format - SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), false); - String privateKeyHex = ByteArray.toHexString(keyPair.getPrivateKey()); - - File keyFile = tempFolder.newFile("sm2.key"); - Files.write(keyFile.toPath(), privateKeyHex.getBytes(StandardCharsets.UTF_8)); - File pwFile = tempFolder.newFile("pw-sm2.txt"); - Files.write(pwFile.toPath(), "test123456".getBytes(StandardCharsets.UTF_8)); - - CommandLine cmd = new CommandLine(new Toolkit()); - int exitCode = cmd.execute("keystore", "import", - "--keystore-dir", dir.getAbsolutePath(), - "--key-file", keyFile.getAbsolutePath(), - "--password-file", pwFile.getAbsolutePath(), - "--sm2"); - - assertEquals("SM2 import should succeed", 0, exitCode); - File[] files = dir.listFiles((d, name) -> name.endsWith(".json")); - assertNotNull(files); - assertEquals(1, files.length); - - // Verify SM2 keystore can be decrypted - Credentials creds = WalletUtils.loadCredentials("test123456", files[0], false); - assertArrayEquals("SM2 key must survive import roundtrip", - keyPair.getPrivateKey(), creds.getSignInterface().getPrivateKey()); - } - @Test public void testImportKeyFileWithWhitespace() throws Exception { File dir = tempFolder.newFolder("keystore-ws"); SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String privateKeyHex = ByteArray.toHexString(keyPair.getPrivateKey()); // Key file with leading/trailing whitespace and newlines @@ -169,7 +138,7 @@ public void testImportKeyFileWithWhitespace() throws Exception { File[] files = dir.listFiles((d, name) -> name.endsWith(".json")); assertNotNull(files); assertEquals(1, files.length); - Credentials creds = WalletUtils.loadCredentials("test123456", files[0], true); + Credentials creds = WalletUtils.loadCredentials("test123456", files[0]); assertArrayEquals("Key must survive whitespace-trimmed import", keyPair.getPrivateKey(), creds.getSignInterface().getPrivateKey()); } @@ -178,7 +147,7 @@ public void testImportKeyFileWithWhitespace() throws Exception { public void testImportDuplicateAddressBlocked() throws Exception { File dir = tempFolder.newFolder("keystore-dup"); SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String privateKeyHex = ByteArray.toHexString(keyPair.getPrivateKey()); File keyFile = tempFolder.newFile("dup.key"); @@ -214,7 +183,7 @@ public void testImportDuplicateAddressBlocked() throws Exception { public void testImportDuplicateAddressWithForce() throws Exception { File dir = tempFolder.newFolder("keystore-force"); SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String privateKeyHex = ByteArray.toHexString(keyPair.getPrivateKey()); File keyFile = tempFolder.newFile("force.key"); @@ -261,7 +230,7 @@ public void testImportKeyFileNotFound() throws Exception { public void testImportWith0xPrefix() throws Exception { File dir = tempFolder.newFolder("keystore-0x"); SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String privateKeyHex = ByteArray.toHexString(keyPair.getPrivateKey()); String expectedAddress = Credentials.create(keyPair).getAddress(); @@ -281,7 +250,7 @@ public void testImportWith0xPrefix() throws Exception { File[] files = dir.listFiles((d, name) -> name.endsWith(".json")); assertNotNull(files); assertEquals(1, files.length); - Credentials creds = WalletUtils.loadCredentials("test123456", files[0], true); + Credentials creds = WalletUtils.loadCredentials("test123456", files[0]); assertEquals("Address must match", expectedAddress, creds.getAddress()); } @@ -289,7 +258,7 @@ public void testImportWith0xPrefix() throws Exception { public void testImportWith0XUppercasePrefix() throws Exception { File dir = tempFolder.newFolder("keystore-0X"); SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String privateKeyHex = ByteArray.toHexString(keyPair.getPrivateKey()); File keyFile = tempFolder.newFile("0X.key"); @@ -311,7 +280,7 @@ public void testImportWith0XUppercasePrefix() throws Exception { public void testImportWarnsOnCorruptedFile() throws Exception { File dir = tempFolder.newFolder("keystore-corrupt"); SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String privateKeyHex = ByteArray.toHexString(keyPair.getPrivateKey()); // Create a corrupted JSON in the keystore dir @@ -347,7 +316,7 @@ public void testImportKeystoreFilePermissions() throws Exception { File dir = tempFolder.newFolder("keystore-perms"); SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String privateKeyHex = ByteArray.toHexString(keyPair.getPrivateKey()); File keyFile = tempFolder.newFile("perm.key"); @@ -384,7 +353,7 @@ public void testImportRefusesSymlinkKeyFile() throws Exception { // Create a real key file and a symlink pointing to it File target = tempFolder.newFile("real.key"); SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); Files.write(target.toPath(), ByteArray.toHexString(keyPair.getPrivateKey()).getBytes(StandardCharsets.UTF_8)); @@ -414,7 +383,7 @@ public void testImportRefusesSymlinkPasswordFile() throws Exception { File dir = tempFolder.newFolder("keystore-pwsymlink"); SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); File keyFile = tempFolder.newFile("sym-pw.key"); Files.write(keyFile.toPath(), ByteArray.toHexString(keyPair.getPrivateKey()).getBytes(StandardCharsets.UTF_8)); @@ -441,7 +410,7 @@ public void testImportRefusesSymlinkPasswordFile() throws Exception { public void testImportDuplicateCheckSkipsInvalidVersion() throws Exception { File dir = tempFolder.newFolder("keystore-badver"); SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String privateKeyHex = ByteArray.toHexString(keyPair.getPrivateKey()); String address = Credentials.create(keyPair).getAddress(); @@ -474,7 +443,7 @@ public void testImportDuplicateScanSkipsSymlinkedEntry() throws Exception { File dir = tempFolder.newFolder("keystore-dup-symlink"); SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String privateKeyHex = ByteArray.toHexString(keyPair.getPrivateKey()); File target = tempFolder.newFile("outside.json"); @@ -510,7 +479,7 @@ public void testImportRejectsMultiLinePasswordFile() throws Exception { // "old\nnew" becomes the password. File dir = tempFolder.newFolder("keystore-multi-pw"); SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String privateKeyHex = ByteArray.toHexString(keyPair.getPrivateKey()); File keyFile = tempFolder.newFile("multi.key"); diff --git a/plugins/src/test/java/org/tron/plugins/KeystoreListTest.java b/plugins/src/test/java/org/tron/plugins/KeystoreListTest.java index 35d3523c87c..fa74d5ba8c8 100644 --- a/plugins/src/test/java/org/tron/plugins/KeystoreListTest.java +++ b/plugins/src/test/java/org/tron/plugins/KeystoreListTest.java @@ -31,7 +31,7 @@ public void testListMultipleKeystores() throws Exception { // Create 3 keystores for (int i = 0; i < 3; i++) { SignInterface key = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); WalletUtils.generateWalletFile(password, key, dir, false); } @@ -125,7 +125,7 @@ public void testListJsonOutput() throws Exception { File dir = tempFolder.newFolder("keystore-json"); String password = "test123456"; SignInterface key = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); WalletUtils.generateWalletFile(password, key, dir, false); StringWriter out = new StringWriter(); @@ -151,7 +151,7 @@ public void testListSkipsNonKeystoreFiles() throws Exception { // Create one valid keystore SignInterface key = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); WalletUtils.generateWalletFile(password, key, dir, false); // Create non-keystore files @@ -183,7 +183,7 @@ public void testListWarnsOnCorruptedJsonFiles() throws Exception { // Create one valid keystore SignInterface key = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); WalletUtils.generateWalletFile(password, key, dir, false); // Create a corrupted JSON file @@ -215,7 +215,7 @@ public void testListSkipsInvalidVersionKeystores() throws Exception { // Create one valid keystore SignInterface key = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); WalletUtils.generateWalletFile(password, key, dir, false); // Create a JSON with address and crypto but wrong version @@ -251,7 +251,7 @@ public void testListSkipsSymlinkedKeystoreFile() throws Exception { String password = "test123456"; SignInterface key = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); WalletUtils.generateWalletFile(password, key, dir, false); // A JSON file elsewhere (simulates "target we should not be tricked diff --git a/plugins/src/test/java/org/tron/plugins/KeystoreNewTest.java b/plugins/src/test/java/org/tron/plugins/KeystoreNewTest.java index 26e3a9b9764..0ce5b3dd3f3 100644 --- a/plugins/src/test/java/org/tron/plugins/KeystoreNewTest.java +++ b/plugins/src/test/java/org/tron/plugins/KeystoreNewTest.java @@ -22,6 +22,15 @@ public class KeystoreNewTest { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); + @Test + public void testSm2OptionIsRejected() { + CommandLine cmd = new CommandLine(new Toolkit()); + + int exitCode = cmd.execute("keystore", "new", "--sm2"); + + assertEquals("Removed --sm2 option must be rejected", 2, exitCode); + } + @Test public void testNewKeystoreWithPasswordFile() throws Exception { File dir = tempFolder.newFolder("keystore"); @@ -45,7 +54,7 @@ public void testNewKeystoreWithPasswordFile() throws Exception { assertEquals("Should create exactly one keystore file", 1, files.length); // Verify the file is a valid keystore - Credentials creds = WalletUtils.loadCredentials("test123456", files[0], true); + Credentials creds = WalletUtils.loadCredentials("test123456", files[0]); assertNotNull(creds.getAddress()); assertTrue(creds.getAddress().startsWith("T")); } @@ -141,29 +150,6 @@ public void testNewKeystoreEmptyPassword() throws Exception { err.toString().contains("at least 6 characters")); } - @Test - public void testNewKeystoreWithSm2() throws Exception { - File dir = tempFolder.newFolder("keystore-sm2"); - File pwFile = tempFolder.newFile("pw-sm2.txt"); - Files.write(pwFile.toPath(), "test123456".getBytes(StandardCharsets.UTF_8)); - - CommandLine cmd = new CommandLine(new Toolkit()); - int exitCode = cmd.execute("keystore", "new", - "--keystore-dir", dir.getAbsolutePath(), - "--password-file", pwFile.getAbsolutePath(), - "--sm2"); - - assertEquals("SM2 keystore creation should succeed", 0, exitCode); - File[] files = dir.listFiles((d, name) -> name.endsWith(".json")); - assertNotNull(files); - assertEquals(1, files.length); - - // Verify SM2 keystore can be decrypted with ecKey=false - org.tron.keystore.Credentials creds = - org.tron.keystore.WalletUtils.loadCredentials("test123456", files[0], false); - assertNotNull(creds.getAddress()); - } - @Test public void testNewKeystoreSpecialCharPassword() throws Exception { File dir = tempFolder.newFolder("keystore-special"); @@ -182,7 +168,7 @@ public void testNewKeystoreSpecialCharPassword() throws Exception { assertEquals(1, files.length); // Verify can decrypt with same special-char password - Credentials creds = WalletUtils.loadCredentials(password, files[0], true); + Credentials creds = WalletUtils.loadCredentials(password, files[0]); assertNotNull(creds.getAddress()); } diff --git a/plugins/src/test/java/org/tron/plugins/KeystoreUpdateTest.java b/plugins/src/test/java/org/tron/plugins/KeystoreUpdateTest.java index ed8f81acd32..f5b6e952735 100644 --- a/plugins/src/test/java/org/tron/plugins/KeystoreUpdateTest.java +++ b/plugins/src/test/java/org/tron/plugins/KeystoreUpdateTest.java @@ -37,12 +37,12 @@ public void testUpdatePassword() throws Exception { String newPassword = "newpass456"; SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); byte[] originalKey = keyPair.getPrivateKey(); String fileName = WalletUtils.generateWalletFile(oldPassword, keyPair, dir, true); Credentials creds = WalletUtils.loadCredentials(oldPassword, - new File(dir, fileName), true); + new File(dir, fileName)); String address = creds.getAddress(); File pwFile = tempFolder.newFile("passwords.txt"); @@ -58,7 +58,7 @@ public void testUpdatePassword() throws Exception { // Verify: new password works and key survives Credentials updated = WalletUtils.loadCredentials(newPassword, - new File(dir, fileName), true); + new File(dir, fileName)); assertArrayEquals("Key must survive password change", originalKey, updated.getSignInterface().getPrivateKey()); @@ -74,11 +74,11 @@ public void testUpdateWrongOldPassword() throws Exception { String password = "correct123"; SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String fileName = WalletUtils.generateWalletFile(password, keyPair, dir, true); Credentials creds = WalletUtils.loadCredentials(password, - new File(dir, fileName), true); + new File(dir, fileName)); String address = creds.getAddress(); File pwFile = tempFolder.newFile("wrong.txt"); @@ -98,7 +98,7 @@ public void testUpdateWrongOldPassword() throws Exception { // Verify: original password still works (file unchanged) Credentials unchanged = WalletUtils.loadCredentials(password, - new File(dir, fileName), true); + new File(dir, fileName)); assertEquals(address, unchanged.getAddress()); } @@ -108,7 +108,7 @@ public void testUpdateNonExistentAddress() throws Exception { String password = "test123456"; SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); WalletUtils.generateWalletFile(password, keyPair, dir, true); File pwFile = tempFolder.newFile("pw.txt"); @@ -133,11 +133,11 @@ public void testUpdateNewPasswordTooShort() throws Exception { String password = "test123456"; SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String fileName = WalletUtils.generateWalletFile(password, keyPair, dir, true); Credentials creds = WalletUtils.loadCredentials(password, - new File(dir, fileName), true); + new File(dir, fileName)); File pwFile = tempFolder.newFile("shortpw.txt"); Files.write(pwFile.toPath(), @@ -162,11 +162,11 @@ public void testUpdateWithWindowsLineEndings() throws Exception { String newPassword = "newpass456"; SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); byte[] originalKey = keyPair.getPrivateKey(); String fileName = WalletUtils.generateWalletFile(oldPassword, keyPair, dir, true); Credentials creds = WalletUtils.loadCredentials(oldPassword, - new File(dir, fileName), true); + new File(dir, fileName)); File pwFile = tempFolder.newFile("crlf.txt"); Files.write(pwFile.toPath(), @@ -180,7 +180,7 @@ public void testUpdateWithWindowsLineEndings() throws Exception { assertEquals("Update with CRLF password file should succeed", 0, exitCode); Credentials updated = WalletUtils.loadCredentials(newPassword, - new File(dir, fileName), true); + new File(dir, fileName)); assertArrayEquals("Key must survive update with CRLF passwords", originalKey, updated.getSignInterface().getPrivateKey()); } @@ -192,10 +192,10 @@ public void testUpdateJsonOutput() throws Exception { String newPassword = "newpass456"; SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String fileName = WalletUtils.generateWalletFile(oldPassword, keyPair, dir, true); Credentials creds = WalletUtils.loadCredentials(oldPassword, - new File(dir, fileName), true); + new File(dir, fileName)); File pwFile = tempFolder.newFile("pw-json.txt"); Files.write(pwFile.toPath(), @@ -227,10 +227,10 @@ public void testUpdateWarnsOnCorruptedFile() throws Exception { String password = "test123456"; SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String fileName = WalletUtils.generateWalletFile(password, keyPair, dir, true); Credentials creds = WalletUtils.loadCredentials(password, - new File(dir, fileName), true); + new File(dir, fileName)); Files.write(new File(dir, "corrupted.json").toPath(), "not valid json{{{".getBytes(StandardCharsets.UTF_8)); @@ -259,10 +259,9 @@ public void testUpdatePasswordFileOnlyOneLine() throws Exception { String password = "test123456"; SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String fileName = WalletUtils.generateWalletFile(password, keyPair, dir, true); - Credentials creds = WalletUtils.loadCredentials(password, - new File(dir, fileName), true); + Credentials creds = WalletUtils.loadCredentials(password, new File(dir, fileName)); File pwFile = tempFolder.newFile("oneline.txt"); Files.write(pwFile.toPath(), @@ -290,11 +289,10 @@ public void testUpdatePasswordFileThreeLines() throws Exception { String oldPassword = "oldpass123"; SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); byte[] originalKey = keyPair.getPrivateKey(); String fileName = WalletUtils.generateWalletFile(oldPassword, keyPair, dir, true); - Credentials creds = WalletUtils.loadCredentials(oldPassword, - new File(dir, fileName), true); + Credentials creds = WalletUtils.loadCredentials(oldPassword, new File(dir, fileName)); // Snapshot the keystore bytes so we can verify the file is untouched. byte[] beforeBytes = Files.readAllBytes(new File(dir, fileName).toPath()); @@ -320,8 +318,7 @@ public void testUpdatePasswordFileThreeLines() throws Exception { beforeBytes, afterBytes); // Verify: original password still decrypts the keystore - Credentials unchanged = WalletUtils.loadCredentials(oldPassword, - new File(dir, fileName), true); + Credentials unchanged = WalletUtils.loadCredentials(oldPassword, new File(dir, fileName)); assertArrayEquals("Original key must still be recoverable with old password", originalKey, unchanged.getSignInterface().getPrivateKey()); } @@ -332,10 +329,9 @@ public void testUpdateNoTtyNoPasswordFile() throws Exception { String password = "test123456"; SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String fileName = WalletUtils.generateWalletFile(password, keyPair, dir, true); - Credentials creds = WalletUtils.loadCredentials(password, - new File(dir, fileName), true); + Credentials creds = WalletUtils.loadCredentials(password, new File(dir, fileName)); StringWriter err = new StringWriter(); CommandLine cmd = new CommandLine(new Toolkit()); @@ -354,10 +350,9 @@ public void testUpdatePasswordFileNotFound() throws Exception { String password = "test123456"; SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String fileName = WalletUtils.generateWalletFile(password, keyPair, dir, true); - Credentials creds = WalletUtils.loadCredentials(password, - new File(dir, fileName), true); + Credentials creds = WalletUtils.loadCredentials(password, new File(dir, fileName)); StringWriter err = new StringWriter(); CommandLine cmd = new CommandLine(new Toolkit()); @@ -371,44 +366,13 @@ public void testUpdatePasswordFileNotFound() throws Exception { err.toString().contains("Password file not found")); } - @Test - public void testUpdateSm2Keystore() throws Exception { - File dir = tempFolder.newFolder("keystore-sm2"); - String oldPassword = "oldpass123"; - String newPassword = "newpass456"; - - SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), false); - byte[] originalKey = keyPair.getPrivateKey(); - String fileName = WalletUtils.generateWalletFile(oldPassword, keyPair, dir, true); - Credentials creds = WalletUtils.loadCredentials(oldPassword, - new File(dir, fileName), false); - - File pwFile = tempFolder.newFile("pw-sm2.txt"); - Files.write(pwFile.toPath(), - (oldPassword + "\n" + newPassword).getBytes(StandardCharsets.UTF_8)); - - CommandLine cmd = new CommandLine(new Toolkit()); - int exitCode = cmd.execute("keystore", "update", creds.getAddress(), - "--keystore-dir", dir.getAbsolutePath(), - "--password-file", pwFile.getAbsolutePath(), - "--sm2"); - - assertEquals("SM2 keystore update should succeed", 0, exitCode); - - Credentials updated = WalletUtils.loadCredentials(newPassword, - new File(dir, fileName), false); - assertArrayEquals("SM2 key must survive password change", - originalKey, updated.getSignInterface().getPrivateKey()); - } - @Test public void testUpdateMultipleKeystoresSameAddress() throws Exception { File dir = tempFolder.newFolder("keystore-multi"); String password = "test123456"; SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String address = Credentials.create(keyPair).getAddress(); // Create two keystores for the same address via direct API @@ -441,10 +405,9 @@ public void testUpdatePasswordFileTooLarge() throws Exception { String password = "test123456"; SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String fileName = WalletUtils.generateWalletFile(password, keyPair, dir, true); - Credentials creds = WalletUtils.loadCredentials(password, - new File(dir, fileName), true); + Credentials creds = WalletUtils.loadCredentials(password, new File(dir, fileName)); // Create a password file > 1KB File pwFile = tempFolder.newFile("bigpw.txt"); @@ -471,11 +434,10 @@ public void testUpdatePasswordFileWithBom() throws Exception { String newPassword = "newpass456"; SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); byte[] originalKey = keyPair.getPrivateKey(); String fileName = WalletUtils.generateWalletFile(oldPassword, keyPair, dir, true); - Credentials creds = WalletUtils.loadCredentials(oldPassword, - new File(dir, fileName), true); + Credentials creds = WalletUtils.loadCredentials(oldPassword, new File(dir, fileName)); // Password file with UTF-8 BOM File pwFile = tempFolder.newFile("bom.txt"); @@ -489,8 +451,7 @@ public void testUpdatePasswordFileWithBom() throws Exception { assertEquals("Update with BOM password file should succeed", 0, exitCode); - Credentials updated = WalletUtils.loadCredentials(newPassword, - new File(dir, fileName), true); + Credentials updated = WalletUtils.loadCredentials(newPassword, new File(dir, fileName)); assertArrayEquals("Key must survive update with BOM password file", originalKey, updated.getSignInterface().getPrivateKey()); } @@ -542,11 +503,10 @@ public void testUpdateWithOldMacLineEndings() throws Exception { String newPassword = "newpass456"; SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); byte[] originalKey = keyPair.getPrivateKey(); String fileName = WalletUtils.generateWalletFile(oldPassword, keyPair, dir, true); - Credentials creds = WalletUtils.loadCredentials(oldPassword, - new File(dir, fileName), true); + Credentials creds = WalletUtils.loadCredentials(oldPassword, new File(dir, fileName)); // Password file with old Mac line endings (\r only) File pwFile = tempFolder.newFile("cr.txt"); @@ -560,8 +520,7 @@ public void testUpdateWithOldMacLineEndings() throws Exception { assertEquals("Update with old Mac CR line endings should succeed", 0, exitCode); - Credentials updated = WalletUtils.loadCredentials(newPassword, - new File(dir, fileName), true); + Credentials updated = WalletUtils.loadCredentials(newPassword, new File(dir, fileName)); assertArrayEquals("Key must survive update with CR passwords", originalKey, updated.getSignInterface().getPrivateKey()); } @@ -572,7 +531,7 @@ public void testUpdateSkipsInvalidVersionKeystores() throws Exception { String password = "test123456"; SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String address = Credentials.create(keyPair).getAddress(); // Create a JSON file with correct address but wrong version @@ -605,7 +564,7 @@ public void testUpdateRejectsTamperedAddressKeystore() throws Exception { // Create a real keystore, then tamper with the address field to simulate // a spoofed keystore that claims a different address than its encrypted key. SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String fileName = WalletUtils.generateWalletFile(password, keyPair, dir, true); File keystoreFile = new File(dir, fileName); @@ -647,7 +606,7 @@ public void testUpdatePreservesCorrectDerivedAddress() throws Exception { String newPassword = "newpass456"; SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String fileName = WalletUtils.generateWalletFile(oldPassword, keyPair, dir, true); String originalAddress = Credentials.create(keyPair).getAddress(); @@ -685,10 +644,9 @@ public void testUpdateNarrowsLoosePermissionsTo0600() throws Exception { String newPassword = "newpass456"; SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String fileName = WalletUtils.generateWalletFile(oldPassword, keyPair, dir, true); - Credentials creds = WalletUtils.loadCredentials(oldPassword, - new File(dir, fileName), true); + Credentials creds = WalletUtils.loadCredentials(oldPassword, new File(dir, fileName)); // Deliberately loosen to 0644 before update java.nio.file.Path keystorePath = new File(dir, fileName).toPath(); @@ -729,10 +687,9 @@ public void testUpdateLegacyTipFiresWhenPasswordHasWhitespace() throws Exception String realPassword = "realpass123"; SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String fileName = WalletUtils.generateWalletFile(realPassword, keyPair, dir, true); - Credentials creds = WalletUtils.loadCredentials(realPassword, - new File(dir, fileName), true); + Credentials creds = WalletUtils.loadCredentials(realPassword, new File(dir, fileName)); // Password with internal whitespace that is NOT the real password File pwFile = tempFolder.newFile("pw-ws.txt"); @@ -760,10 +717,9 @@ public void testUpdateLegacyTipSuppressedWhenPasswordHasNoWhitespace() throws Ex String realPassword = "realpass123"; SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String fileName = WalletUtils.generateWalletFile(realPassword, keyPair, dir, true); - Credentials creds = WalletUtils.loadCredentials(realPassword, - new File(dir, fileName), true); + Credentials creds = WalletUtils.loadCredentials(realPassword, new File(dir, fileName)); // Wrong password with no whitespace File pwFile = tempFolder.newFile("pw-nows.txt"); @@ -794,10 +750,9 @@ public void testUpdateScanSkipsSymlinkedEntry() throws Exception { String newPassword = "newpass456"; SignInterface keyPair = SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"), true); + SecureRandom.getInstance("NativePRNG")); String fileName = WalletUtils.generateWalletFile(oldPassword, keyPair, dir, true); - Credentials creds = WalletUtils.loadCredentials(oldPassword, - new File(dir, fileName), true); + Credentials creds = WalletUtils.loadCredentials(oldPassword, new File(dir, fileName)); File target = tempFolder.newFile("outside.json"); Files.write(target.toPath(),