From de3667aa4dfd8004ed521c518de3a87f8ed09749 Mon Sep 17 00:00:00 2001 From: yg3630536 <125480926@qq.com> Date: Fri, 27 Nov 2020 18:15:33 +0800 Subject: [PATCH 1/6] * query cpt List and Count --- CHANGELOG.md | 8 +++++ build.gradle | 2 +- .../weid/rpc/AuthorityIssuerService.java | 6 ++++ .../java/com/webank/weid/rpc/CptService.java | 18 ++++++++++ .../com/webank/weid/rpc/PolicyService.java | 7 ++++ .../impl/AuthorityIssuerServiceImpl.java | 5 +++ .../weid/service/impl/CptServiceImpl.java | 18 ++++++++-- .../weid/service/impl/PolicyServiceImpl.java | 7 +++- .../engine/AuthorityIssuerServiceEngine.java | 6 ++++ .../service/impl/engine/CptServiceEngine.java | 20 ++++++++++- .../engine/fiscov1/CptServiceEngineV1.java | 0 .../fiscov2/AuthorityIssuerEngineV2.java | 11 +++++++ .../engine/fiscov2/CptServiceEngineV2.java | 33 ++++++++++++++++--- .../com/webank/weid/util/DataToolUtils.java | 1 + 14 files changed, 131 insertions(+), 11 deletions(-) delete mode 100644 src/main/java/com/webank/weid/service/impl/engine/fiscov1/CptServiceEngineV1.java diff --git a/CHANGELOG.md b/CHANGELOG.md index bc6ab576f..4ddebdce7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,11 @@ +### V1.7.0 +Features: +1. FISCO BCOS 1.3.x support is fully removed - please use the FISCO BCOS 2.x node version respectively. +2. Evidence and WeIdDocument query performance improved due to support batch type blockchain node data lookup. +3. Authority Issuer can be registered by any WeID while only administrator can recognize. +4. Greatly enhanced WeID-Build-Tools functionalities. +5. Persistence now supports Redis as storage layer. + ### V1.6.3-hotfix-1 (2020-08-26) - Bugfixes: 1. Use batch block transaction receipts getter to improve evidence performance. diff --git a/build.gradle b/build.gradle index c3185ccd2..8a7353b9f 100644 --- a/build.gradle +++ b/build.gradle @@ -153,7 +153,7 @@ dependencies { localDeps 'org.projectlombok:lombok:1.18.10' if (!gradle.startParameter.isOffline()) { compile logger, lombok, apache_commons, json, mysql_driver, redisson, zxing, rpc, pdfbox, protobuf, caffeine, oval - compile("com.webank:weid-contract-java:1.2.28") { + compile("com.webank:weid-contract-java:1.2.29-rc.2-SNAPSHOT") { exclude group: "org.slf4j", module: "slf4j-log4j12" } compile fileTree(dir: 'lib', include: '*.jar') diff --git a/src/main/java/com/webank/weid/rpc/AuthorityIssuerService.java b/src/main/java/com/webank/weid/rpc/AuthorityIssuerService.java index 3f921d0fb..80a7ebfe6 100644 --- a/src/main/java/com/webank/weid/rpc/AuthorityIssuerService.java +++ b/src/main/java/com/webank/weid/rpc/AuthorityIssuerService.java @@ -169,4 +169,10 @@ ResponseData> getAllSpecificTypeIssuerList( * @return WeID */ ResponseData getWeIdByOrgId(String orgId); + + /** + * get the issuer count. + * @return the all issuer + */ + ResponseData getIssuerCount(); } diff --git a/src/main/java/com/webank/weid/rpc/CptService.java b/src/main/java/com/webank/weid/rpc/CptService.java index c60e8c41a..d3163e5a3 100644 --- a/src/main/java/com/webank/weid/rpc/CptService.java +++ b/src/main/java/com/webank/weid/rpc/CptService.java @@ -19,6 +19,8 @@ package com.webank.weid.rpc; +import java.util.List; + import com.webank.wedpr.selectivedisclosure.CredentialTemplateEntity; import com.webank.weid.protocol.base.Cpt; @@ -101,4 +103,20 @@ public interface CptService { * @return The updated CPT info */ ResponseData queryCredentialTemplate(Integer cptId); + + /** + * Get CPTIDS from chain. + * + * @param startPos start position + * @param num batch number + * @return CPTID list + */ + ResponseData> getCptIdList(Integer startPos, Integer num); + + /** + * Get CPT count. + * + * @return the cpt count + */ + ResponseData getCptCount(); } diff --git a/src/main/java/com/webank/weid/rpc/PolicyService.java b/src/main/java/com/webank/weid/rpc/PolicyService.java index c4e22912a..0bafcc198 100644 --- a/src/main/java/com/webank/weid/rpc/PolicyService.java +++ b/src/main/java/com/webank/weid/rpc/PolicyService.java @@ -86,4 +86,11 @@ ResponseData registerPresentationPolicy(List claimPolicyIdList * @return claim policy list */ ResponseData> getAllClaimPolicies(Integer startPos, Integer num); + + /** + * Get Policy count. + * + * @return the Policy count + */ + ResponseData getPolicyCount(); } diff --git a/src/main/java/com/webank/weid/service/impl/AuthorityIssuerServiceImpl.java b/src/main/java/com/webank/weid/service/impl/AuthorityIssuerServiceImpl.java index 31b108b55..d80dae110 100644 --- a/src/main/java/com/webank/weid/service/impl/AuthorityIssuerServiceImpl.java +++ b/src/main/java/com/webank/weid/service/impl/AuthorityIssuerServiceImpl.java @@ -535,4 +535,9 @@ public ResponseData getWeIdByOrgId(String orgId) { return new ResponseData<>(StringUtils.EMPTY, ErrorCode.AUTHORITY_ISSUER_ERROR); } } + + @Override + public ResponseData getIssuerCount() { + return authEngine.getIssuerCount(); + } } diff --git a/src/main/java/com/webank/weid/service/impl/CptServiceImpl.java b/src/main/java/com/webank/weid/service/impl/CptServiceImpl.java index 0e865dcf7..c1a624d8d 100644 --- a/src/main/java/com/webank/weid/service/impl/CptServiceImpl.java +++ b/src/main/java/com/webank/weid/service/impl/CptServiceImpl.java @@ -21,6 +21,7 @@ import java.math.BigInteger; import java.util.HashMap; +import java.util.List; import java.util.Map; import com.webank.wedpr.selectivedisclosure.CredentialTemplateEntity; @@ -29,9 +30,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.webank.weid.constant.CredentialConstant; import com.webank.weid.constant.ErrorCode; -import com.webank.weid.constant.JsonSchemaConstant; import com.webank.weid.constant.WeIdConstant; import com.webank.weid.protocol.base.Cpt; import com.webank.weid.protocol.base.CptBaseInfo; @@ -371,7 +370,20 @@ private ErrorCode validateCptJsonSchemaMap( */ @Override public ResponseData queryCredentialTemplate(Integer cptId) { - return cptServiceEngine.queryCredentialTemplate(cptId); } + + + @Override + public ResponseData> getCptIdList(Integer startPos, Integer num) { + if (startPos < 0 || num < 1) { + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + return cptServiceEngine.getCptIdList(startPos, num, WeIdConstant.CPT_DATA_INDEX); + } + + @Override + public ResponseData getCptCount() { + return cptServiceEngine.getCptCount(WeIdConstant.CPT_DATA_INDEX); + } } diff --git a/src/main/java/com/webank/weid/service/impl/PolicyServiceImpl.java b/src/main/java/com/webank/weid/service/impl/PolicyServiceImpl.java index 545d4a6ac..14a7b79a9 100644 --- a/src/main/java/com/webank/weid/service/impl/PolicyServiceImpl.java +++ b/src/main/java/com/webank/weid/service/impl/PolicyServiceImpl.java @@ -218,6 +218,11 @@ public ResponseData> getAllClaimPolicies(Integer startPos, Integer if (startPos < 0 || num < 1) { return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); } - return cptServiceEngine.getCptLists(startPos, num, WeIdConstant.POLICY_DATA_INDEX); + return cptServiceEngine.getCptIdList(startPos, num, WeIdConstant.POLICY_DATA_INDEX); + } + + @Override + public ResponseData getPolicyCount() { + return cptServiceEngine.getCptCount(WeIdConstant.POLICY_DATA_INDEX); } } diff --git a/src/main/java/com/webank/weid/service/impl/engine/AuthorityIssuerServiceEngine.java b/src/main/java/com/webank/weid/service/impl/engine/AuthorityIssuerServiceEngine.java index 54d0cb302..7dbb82fe5 100644 --- a/src/main/java/com/webank/weid/service/impl/engine/AuthorityIssuerServiceEngine.java +++ b/src/main/java/com/webank/weid/service/impl/engine/AuthorityIssuerServiceEngine.java @@ -138,4 +138,10 @@ public ResponseData addIssuer( public ResponseData getWeIdFromOrgId(String orgId); public ResponseData recognizeWeId(Boolean isRecognize, String addr, String privateKey); + + /** + * get the issuer count. + * @return the all issuer + */ + public ResponseData getIssuerCount(); } diff --git a/src/main/java/com/webank/weid/service/impl/engine/CptServiceEngine.java b/src/main/java/com/webank/weid/service/impl/engine/CptServiceEngine.java index eddce5466..7bc807ef7 100644 --- a/src/main/java/com/webank/weid/service/impl/engine/CptServiceEngine.java +++ b/src/main/java/com/webank/weid/service/impl/engine/CptServiceEngine.java @@ -45,6 +45,7 @@ public interface CptServiceEngine extends ReloadStaticContract { * @param cptJsonSchemaNew cpt content * @param rsvSignature signature * @param privateKey private key + * @param dataStorageIndex 0 is cpt, 1 is policy * @return result */ ResponseData updateCpt( @@ -64,6 +65,7 @@ ResponseData updateCpt( * @param cptJsonSchemaNew cpt content * @param rsvSignature signature * @param privateKey private key + * @param dataStorageIndex 0 is cpt, 1 is policy * @return result */ ResponseData registerCpt( @@ -82,6 +84,7 @@ ResponseData registerCpt( * @param cptJsonSchemaNew cpt content * @param rsvSignature signature * @param privateKey private key + * @param dataStorageIndex 0 is cpt, 1 is policy * @return result */ ResponseData registerCpt( @@ -96,6 +99,7 @@ ResponseData registerCpt( * call cpt contract method to query cpt info from blockchain. * * @param cptId the id of the cpt + * @param dataStorageIndex 0 is cpt, 1 is policy * @return cpt info */ ResponseData queryCpt(int cptId, int dataStorageIndex); @@ -118,5 +122,19 @@ ResponseData putPolicyIntoCpt(Integer cptId, List policyIdList ResponseData> getPolicyFromCpt(Integer cptId); - ResponseData> getCptLists(int startPos, int num, int dataStorageIndex); + /** + * 分页查询cptId列表. + * @param startPos 起始位置 + * @param num 查询数量 + * @param dataStorageIndex 存储类型,0表示CPT,1表示policy + * @return 返回id列表 + */ + ResponseData> getCptIdList(int startPos, int num, int dataStorageIndex); + + /** + * 查询cpt或者policy总数. + * @param dataStorageIndex 存储类型,0表示CPT,1表示policy + * @return 返回总数 + */ + ResponseData getCptCount(int dataStorageIndex); } diff --git a/src/main/java/com/webank/weid/service/impl/engine/fiscov1/CptServiceEngineV1.java b/src/main/java/com/webank/weid/service/impl/engine/fiscov1/CptServiceEngineV1.java deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/main/java/com/webank/weid/service/impl/engine/fiscov2/AuthorityIssuerEngineV2.java b/src/main/java/com/webank/weid/service/impl/engine/fiscov2/AuthorityIssuerEngineV2.java index abdf0540e..c6ccb45c5 100644 --- a/src/main/java/com/webank/weid/service/impl/engine/fiscov2/AuthorityIssuerEngineV2.java +++ b/src/main/java/com/webank/weid/service/impl/engine/fiscov2/AuthorityIssuerEngineV2.java @@ -556,4 +556,15 @@ public ResponseData addIssuer(String issuerType, String issuerAddress, } } + @Override + public ResponseData getIssuerCount() { + try { + Integer count = authorityIssuerController.getTotalIssuer().send().intValue(); + return new ResponseData<>(count, ErrorCode.SUCCESS); + } catch (Exception e) { + logger.error("[getCptCount] query CptCount failed. exception message: ", e); + return new ResponseData<>(0, ErrorCode.TRANSACTION_EXECUTE_ERROR); + } + } + } diff --git a/src/main/java/com/webank/weid/service/impl/engine/fiscov2/CptServiceEngineV2.java b/src/main/java/com/webank/weid/service/impl/engine/fiscov2/CptServiceEngineV2.java index bbf5bde3a..14d64d0a6 100644 --- a/src/main/java/com/webank/weid/service/impl/engine/fiscov2/CptServiceEngineV2.java +++ b/src/main/java/com/webank/weid/service/impl/engine/fiscov2/CptServiceEngineV2.java @@ -706,19 +706,42 @@ public ResponseData> getPolicyFromCpt(Integer cptId) { } @Override - public ResponseData> getCptLists(int startPos, int num, int dataStorageIndex) { + public ResponseData> getCptIdList(int startPos, int num, int dataStorageIndex) { try { - List list = cptController.getCptIdList( - new BigInteger(String.valueOf(startPos), 10), - new BigInteger(String.valueOf(num), 10)).send(); + List list = null; + if (dataStorageIndex == WeIdConstant.CPT_DATA_INDEX) { + list = cptController.getCptIdList( + new BigInteger(String.valueOf(startPos), 10), + new BigInteger(String.valueOf(num), 10)).send(); + } else { + list = cptController.getPolicyIdList( + new BigInteger(String.valueOf(startPos), 10), + new BigInteger(String.valueOf(num), 10)).send(); + } List cpts = new ArrayList<>(); for (Object obj : list) { cpts.add(((BigInteger) obj).intValue()); } return new ResponseData<>(cpts, ErrorCode.SUCCESS); } catch (Exception e) { - logger.error("[queryCpt] query Cpt failed. exception message: ", e); + logger.error("[getCptIdList] query CptLists failed. exception message: ", e); return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); } } + + @Override + public ResponseData getCptCount(int dataStorageIndex) { + try { + Integer count = null; + if (dataStorageIndex == WeIdConstant.CPT_DATA_INDEX) { + count = cptController.getTotalCptId().send().intValue(); + } else { + count = cptController.getTotalPolicyId().send().intValue(); + } + return new ResponseData<>(count, ErrorCode.SUCCESS); + } catch (Exception e) { + logger.error("[getCptCount] query CptCount failed. exception message: ", e); + return new ResponseData<>(0, ErrorCode.TRANSACTION_EXECUTE_ERROR); + } + } } diff --git a/src/main/java/com/webank/weid/util/DataToolUtils.java b/src/main/java/com/webank/weid/util/DataToolUtils.java index d1d74c1d4..7d36db783 100644 --- a/src/main/java/com/webank/weid/util/DataToolUtils.java +++ b/src/main/java/com/webank/weid/util/DataToolUtils.java @@ -1568,6 +1568,7 @@ public static synchronized String byte32ListToString(List bytesList, int public static List getParamCreatedList(int length) { long created = DateUtils.getNoMillisecondTimeStamp(); List createdList = new ArrayList<>(); + createdList.add(BigInteger.ZERO); createdList.add(BigInteger.valueOf(created)); return createdList; } From d4c3791235efbf8cab73ff463422eaeb2618767b Mon Sep 17 00:00:00 2001 From: anyspa Date: Fri, 8 Jan 2021 15:12:24 +0800 Subject: [PATCH 2/6] support fisco gm --- build.gradle | 2 +- docs/zh_CN/docs/weidentity-java-sdk-doc.rst | 2 +- .../com/webank/weid/config/FiscoConfig.java | 25 ++++ .../weid/service/fisco/WeServerUtils.java | 35 +++++- .../weid/service/fisco/v2/WeServerV2.java | 6 +- .../impl/CredentialPojoServiceImpl.java | 6 +- .../service/impl/CredentialServiceImpl.java | 2 +- .../weid/service/impl/WeIdServiceImpl.java | 11 +- .../com/webank/weid/util/DataToolUtils.java | 117 +++++++++++++----- .../webank/weid/util/OffLineBatchTask.java | 4 +- .../java/com/webank/weid/util/WeIdUtils.java | 14 ++- src/main/resources/fisco.properties.tpl | 10 +- .../com/webank/weid/full/TestBaseService.java | 65 ++++------ .../com/webank/weid/full/TestBaseUtil.java | 47 +++++-- .../auth/TestRegisterAuthorityIssuer.java | 2 +- .../full/cpt/TestRegisterCptStringArgs.java | 1 - .../TestCreateCredentialPojo.java | 6 +- .../weid/full/weid/TestCreateWeId1.java | 25 +--- .../full/weid/TestGetWeIdDocumentJson.java | 1 - .../weid/full/weid/TestSetAuthentication.java | 2 +- .../webank/weid/util/TestBuildPrivateKey.java | 4 +- .../java/com/webank/weid/util/TestCrypt.java | 8 +- .../webank/weid/util/TestSignatureUtils.java | 11 +- .../com/webank/weid/util/TestWeIdUtils.java | 4 +- 24 files changed, 260 insertions(+), 150 deletions(-) diff --git a/build.gradle b/build.gradle index c3185ccd2..8a7353b9f 100644 --- a/build.gradle +++ b/build.gradle @@ -153,7 +153,7 @@ dependencies { localDeps 'org.projectlombok:lombok:1.18.10' if (!gradle.startParameter.isOffline()) { compile logger, lombok, apache_commons, json, mysql_driver, redisson, zxing, rpc, pdfbox, protobuf, caffeine, oval - compile("com.webank:weid-contract-java:1.2.28") { + compile("com.webank:weid-contract-java:1.2.29-rc.2-SNAPSHOT") { exclude group: "org.slf4j", module: "slf4j-log4j12" } compile fileTree(dir: 'lib', include: '*.jar') diff --git a/docs/zh_CN/docs/weidentity-java-sdk-doc.rst b/docs/zh_CN/docs/weidentity-java-sdk-doc.rst index 892bf9eed..edb7c13ca 100644 --- a/docs/zh_CN/docs/weidentity-java-sdk-doc.rst +++ b/docs/zh_CN/docs/weidentity-java-sdk-doc.rst @@ -13752,7 +13752,7 @@ com.webank.weid.protocol.base.CredentialPojo // Enforce a Register/Update system CPT first WeIdAuthentication sdkAuthen = new WeIdAuthentication(); - ECKeyPair keyPair = ECKeyPair.create(new BigInteger(privateKey)); + ECKeyPair keyPair = DataToolUtils.createKeyPairFromPrivate(privateKey); String keyWeId = WeIdUtils .convertAddressToWeId(new Address(Keys.getAddress(keyPair)).toString()); sdkAuthen.setWeId(keyWeId); diff --git a/src/main/java/com/webank/weid/config/FiscoConfig.java b/src/main/java/com/webank/weid/config/FiscoConfig.java index 7da51e3d0..cb193897e 100644 --- a/src/main/java/com/webank/weid/config/FiscoConfig.java +++ b/src/main/java/com/webank/weid/config/FiscoConfig.java @@ -132,6 +132,26 @@ public class FiscoConfig { @NotNull(message = "the v2.node-key-path is undefined") @NotEmpty(message = "the value of v2.node-key-path is null") private String v2NodeKeyPath; + + @NotNull(message = "the gm.ca-crt-path is undefined") + @NotEmpty(message = "the value of gm.ca-crt-path is null") + private String gmCaCrtPath; + + @NotNull(message = "the gm.sdk-crt-path is undefined") + @NotEmpty(message = "the value of gm.sdk-crt-path is null") + private String gmSdkCrtPath; + + @NotNull(message = "the gm.sdk-key-path is undefined") + @NotEmpty(message = "the value of gm.sdk-key-path is null") + private String gmSdkKeyPath; + + @NotNull(message = "the gmen.sdk-crt-path is undefined") + @NotEmpty(message = "the value of gmen.sdk-crt-path is null") + private String gmenSdkCrtPath; + + @NotNull(message = "the gmen.sdk-key-path is undefined") + @NotEmpty(message = "the value of gmen.sdk-key-path is null") + private String gmenSdkKeyPath; @NotNull(message = "the blockchain.orgid is undefined") @NotEmpty(message = "the value of blockchain.orgid is null") @@ -174,6 +194,11 @@ public boolean load() { v2CaCrtPath = PropertyUtils.getProperty("v2.ca-crt-path"); v2NodeCrtPath = PropertyUtils.getProperty("v2.node-crt-path"); v2NodeKeyPath = PropertyUtils.getProperty("v2.node-key-path"); + gmCaCrtPath = PropertyUtils.getProperty("gm.ca-crt-path"); + gmSdkCrtPath = PropertyUtils.getProperty("gm.sdk-crt-path"); + gmSdkKeyPath = PropertyUtils.getProperty("gm.sdk-key-path"); + gmenSdkCrtPath = PropertyUtils.getProperty("gmen.sdk-crt-path"); + gmenSdkKeyPath = PropertyUtils.getProperty("gmen.sdk-key-path"); currentOrgId = PropertyUtils.getProperty("blockchain.orgid"); amopId = PropertyUtils.getProperty("amop.id"); cnsContractFollow = PropertyUtils.getProperty("cns.contract.follow"); diff --git a/src/main/java/com/webank/weid/service/fisco/WeServerUtils.java b/src/main/java/com/webank/weid/service/fisco/WeServerUtils.java index d6894ec8b..72e9a51f0 100644 --- a/src/main/java/com/webank/weid/service/fisco/WeServerUtils.java +++ b/src/main/java/com/webank/weid/service/fisco/WeServerUtils.java @@ -33,6 +33,7 @@ import org.fisco.bcos.channel.client.Service; import org.fisco.bcos.channel.handler.ChannelConnections; import org.fisco.bcos.channel.handler.GroupChannelConnectionsConfig; +import org.fisco.bcos.web3j.crypto.EncryptType; import org.fisco.bcos.web3j.protocol.Web3j; import org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService; import org.slf4j.Logger; @@ -146,12 +147,34 @@ public static GroupChannelConnectionsConfig buildGroupChannelConnectionsConfig( ChannelConnections channelConnections = new ChannelConnections(); channelConnections.setGroupId(groupId); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); - channelConnections - .setCaCert(resolver.getResource("classpath:" + fiscoConfig.getV2CaCrtPath())); - channelConnections - .setSslCert(resolver.getResource("classpath:" + fiscoConfig.getV2NodeCrtPath())); - channelConnections - .setSslKey(resolver.getResource("classpath:" + fiscoConfig.getV2NodeKeyPath())); + + if (fiscoConfig.getEncryptType().equals(String.valueOf(EncryptType.ECDSA_TYPE))) { + EncryptType encryptType = new EncryptType(EncryptType.ECDSA_TYPE); + channelConnections.setCaCert( + resolver.getResource("classpath:" + fiscoConfig.getV2CaCrtPath())); + channelConnections.setSslCert( + resolver.getResource("classpath:" + fiscoConfig.getV2NodeCrtPath())); + channelConnections.setSslKey( + resolver.getResource("classpath:" + fiscoConfig.getV2NodeKeyPath())); + } else { + EncryptType encryptType = new EncryptType(EncryptType.SM2_TYPE); + + // gmca.crt + channelConnections.setGmCaCert( + resolver.getResource("classpath:" + fiscoConfig.getGmCaCrtPath())); + // gmsdk.crt + channelConnections.setGmSslCert( + resolver.getResource("classpath:" + fiscoConfig.getGmSdkCrtPath())); + // gmsdk.key + channelConnections.setGmSslKey( + resolver.getResource("classpath:" + fiscoConfig.getGmSdkKeyPath())); + // gmensdk.crt + channelConnections.setGmEnSslCert( + resolver.getResource("classpath:" + fiscoConfig.getGmenSdkCrtPath())); + // gmensdk.key + channelConnections.setGmEnSslKey( + resolver.getResource("classpath:" + fiscoConfig.getGmenSdkKeyPath())); + } channelConnections.setConnectionsStr(nodeList); GroupChannelConnectionsConfig connectionsConfig = new GroupChannelConnectionsConfig(); diff --git a/src/main/java/com/webank/weid/service/fisco/v2/WeServerV2.java b/src/main/java/com/webank/weid/service/fisco/v2/WeServerV2.java index 68bd0990c..8bca35856 100644 --- a/src/main/java/com/webank/weid/service/fisco/v2/WeServerV2.java +++ b/src/main/java/com/webank/weid/service/fisco/v2/WeServerV2.java @@ -24,6 +24,7 @@ import java.util.List; import org.apache.commons.collections4.CollectionUtils; + import org.fisco.bcos.channel.client.ChannelPushCallback; import org.fisco.bcos.channel.client.Service; import org.fisco.bcos.channel.dto.ChannelRequest; @@ -51,6 +52,7 @@ import com.webank.weid.service.fisco.WeServer; import com.webank.weid.service.fisco.WeServerUtils; import com.webank.weid.service.impl.base.AmopCommonArgs; +import com.webank.weid.util.DataToolUtils; public final class WeServerV2 extends WeServer { @@ -89,8 +91,8 @@ public Credentials getCredentials() { public Credentials createCredentials(String privateKey) { Credentials credentials; try { - ECKeyPair keyPair = ECKeyPair.create(new BigInteger(privateKey)); - credentials = Credentials.create(keyPair); + ECKeyPair keyPair = DataToolUtils.createKeyPairFromPrivate(new BigInteger(privateKey)); + credentials = GenCredential.create(keyPair); return credentials; } catch (Exception e) { throw new PrivateKeyIllegalException(e); diff --git a/src/main/java/com/webank/weid/service/impl/CredentialPojoServiceImpl.java b/src/main/java/com/webank/weid/service/impl/CredentialPojoServiceImpl.java index 40dae7978..bbc479cbd 100644 --- a/src/main/java/com/webank/weid/service/impl/CredentialPojoServiceImpl.java +++ b/src/main/java/com/webank/weid/service/impl/CredentialPojoServiceImpl.java @@ -1181,7 +1181,7 @@ public ResponseData addSignature( return new ResponseData<>(null, ErrorCode.WEID_DOES_NOT_EXIST); } String privateKey = callerAuth.getWeIdPrivateKey().getPrivateKey(); - ECKeyPair keyPair = ECKeyPair.create(new BigInteger(privateKey)); + ECKeyPair keyPair = DataToolUtils.createKeyPairFromPrivate(new BigInteger(privateKey)); String keyWeId = WeIdUtils .convertAddressToWeId(new Address(Keys.getAddress(keyPair)).toString()); result.setIssuer(keyWeId); @@ -1985,7 +1985,7 @@ public ResponseData createTrustedTimestamp( CredentialPojo credential = new CredentialPojo(); credential.setCptId(CredentialConstant.EMBEDDED_TIMESTAMP_CPT); String privateKey = weIdAuthentication.getWeIdPrivateKey().getPrivateKey(); - ECKeyPair keyPair = ECKeyPair.create(new BigInteger(privateKey)); + ECKeyPair keyPair = DataToolUtils.createKeyPairFromPrivate(new BigInteger(privateKey)); String keyWeId = WeIdUtils .convertAddressToWeId(new Address(Keys.getAddress(keyPair)).toString()); credential.setIssuer(keyWeId); @@ -2249,7 +2249,7 @@ public ResponseData createDataAuthToken( args.setContext(CredentialUtils.getDefaultCredentialContext()); args.setCptId(CredentialConstant.AUTHORIZATION_CPT); String privateKey = weIdAuthentication.getWeIdPrivateKey().getPrivateKey(); - ECKeyPair keyPair = ECKeyPair.create(new BigInteger(privateKey)); + ECKeyPair keyPair = DataToolUtils.createKeyPairFromPrivate(new BigInteger(privateKey)); String keyWeId = WeIdUtils .convertAddressToWeId(new Address(Keys.getAddress(keyPair)).toString()); args.setIssuer(keyWeId); diff --git a/src/main/java/com/webank/weid/service/impl/CredentialServiceImpl.java b/src/main/java/com/webank/weid/service/impl/CredentialServiceImpl.java index cae6fb346..f6bd8bb9e 100644 --- a/src/main/java/com/webank/weid/service/impl/CredentialServiceImpl.java +++ b/src/main/java/com/webank/weid/service/impl/CredentialServiceImpl.java @@ -191,7 +191,7 @@ public ResponseData addSignature( result.setExpirationDate(newExpirationDate); } String privateKey = weIdPrivateKey.getPrivateKey(); - ECKeyPair keyPair = ECKeyPair.create(new BigInteger(privateKey)); + ECKeyPair keyPair = DataToolUtils.createKeyPairFromPrivate(new BigInteger(privateKey)); String keyWeId = WeIdUtils .convertAddressToWeId(new Address(Keys.getAddress(keyPair)).toString()); if (!weIdService.isWeIdExist(keyWeId).getResult()) { diff --git a/src/main/java/com/webank/weid/service/impl/WeIdServiceImpl.java b/src/main/java/com/webank/weid/service/impl/WeIdServiceImpl.java index fbbc4ed5f..6ffa86c0a 100644 --- a/src/main/java/com/webank/weid/service/impl/WeIdServiceImpl.java +++ b/src/main/java/com/webank/weid/service/impl/WeIdServiceImpl.java @@ -21,12 +21,13 @@ import java.nio.charset.StandardCharsets; import java.util.List; +import java.util.Objects; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.fisco.bcos.web3j.crypto.ECKeyPair; -import org.fisco.bcos.web3j.crypto.Keys; +import org.fisco.bcos.web3j.crypto.gm.GenCredential; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -71,12 +72,10 @@ public class WeIdServiceImpl extends AbstractService implements WeIdService { public ResponseData createWeId() { CreateWeIdDataResult result = new CreateWeIdDataResult(); - ECKeyPair keyPair = null; + ECKeyPair keyPair = GenCredential.createKeyPair(); - try { - keyPair = Keys.createEcKeyPair(); - } catch (Exception e) { - logger.error("Create weId failed.", e); + if (Objects.isNull(keyPair)) { + logger.error("Create weId failed."); return new ResponseData<>(null, ErrorCode.WEID_KEYPAIR_CREATE_FAILED); } diff --git a/src/main/java/com/webank/weid/util/DataToolUtils.java b/src/main/java/com/webank/weid/util/DataToolUtils.java index d1d74c1d4..c71b75d27 100644 --- a/src/main/java/com/webank/weid/util/DataToolUtils.java +++ b/src/main/java/com/webank/weid/util/DataToolUtils.java @@ -90,10 +90,14 @@ import org.fisco.bcos.web3j.crypto.ECDSASign; import org.fisco.bcos.web3j.crypto.ECDSASignature; import org.fisco.bcos.web3j.crypto.ECKeyPair; +import org.fisco.bcos.web3j.crypto.EncryptType; import org.fisco.bcos.web3j.crypto.Hash; import org.fisco.bcos.web3j.crypto.Keys; import org.fisco.bcos.web3j.crypto.Sign; import org.fisco.bcos.web3j.crypto.Sign.SignatureData; +import org.fisco.bcos.web3j.crypto.gm.GenCredential; +import org.fisco.bcos.web3j.crypto.gm.sm2.SM2Sign; +import org.fisco.bcos.web3j.crypto.gm.sm3.SM3Digest; import org.fisco.bcos.web3j.crypto.tool.ECCDecrypt; import org.fisco.bcos.web3j.crypto.tool.ECCEncrypt; import org.fisco.bcos.web3j.utils.Numeric; @@ -153,6 +157,8 @@ public final class DataToolUtils { //private static final ObjectReader OBJECT_READER; private static final ObjectWriter OBJECT_WRITER_UN_PRETTY_PRINTER; + private static final String encryptType; + static { // sort by letter OBJECT_MAPPER.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true); @@ -172,6 +178,8 @@ public final class DataToolUtils { CONVERT_UTC_LONG_KEYLIST.add(KEY_ISSUANCEDATE); CONVERT_UTC_LONG_KEYLIST.add(KEY_EXPIRATIONDATE); + encryptType = PropertyUtils.getProperty("encrypt.type"); + //OBJECT_WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter(); //OBJECT_READER = OBJECT_MAPPER.reader(); } @@ -241,11 +249,15 @@ public static String serialize(T object) { * @return true if yes, false otherwise */ public static String convertPrivateKeyToDefaultWeId(String privateKey) { - ECKeyPair keyPair = ECKeyPair - .create(new BigInteger(privateKey)); + BigInteger publicKey; + if (encryptType.equals(String.valueOf(EncryptType.ECDSA_TYPE))) { + publicKey = Sign.publicKeyFromPrivate(new BigInteger(privateKey)); + } else { + publicKey = Sign.smPublicKeyFromPrivate(new BigInteger(privateKey)); + } return WeIdUtils .convertAddressToWeId(new org.fisco.bcos.web3j.abi.datatypes.Address( - Keys.getAddress(keyPair)).toString()); + Keys.getAddress(publicKey)).toString()); } /** @@ -517,11 +529,15 @@ public static String cptSchemaToString(CptMapArgs args) { * @throws NoSuchAlgorithmException No such algorithm. * @throws NoSuchProviderException No such provider. */ - public static ECKeyPair createKeyPair() - throws InvalidAlgorithmParameterException, - NoSuchAlgorithmException, - NoSuchProviderException { - return Keys.createEcKeyPair(); + public static ECKeyPair createKeyPair() throws + InvalidAlgorithmParameterException, + NoSuchAlgorithmException, + NoSuchProviderException { + if (encryptType.equals(String.valueOf(EncryptType.ECDSA_TYPE))) { + return Keys.createEcKeyPair(); + } else { + return GenCredential.createGuomiKeyPair(); + } } /** @@ -544,8 +560,13 @@ public static String secp256k1Sign(String rawData, BigInteger privateKey) { * @return SignatureData for signature value */ public static SignatureData secp256k1SignToSignature(String rawData, ECKeyPair keyPair) { - ECDSASign ecdsaSign = new ECDSASign(); - return ecdsaSign.secp256SignMessage(rawData.getBytes(), keyPair); + if (encryptType.equals(String.valueOf(EncryptType.ECDSA_TYPE))) { + ECDSASign ecdsaSign = new ECDSASign(); + return ecdsaSign.secp256SignMessage(rawData.getBytes(), keyPair); + } else { + return SM2Sign.sign(rawData.getBytes(), keyPair); + } + } /** @@ -556,7 +577,7 @@ public static SignatureData secp256k1SignToSignature(String rawData, ECKeyPair k * @return SignatureData for signature value */ public static SignatureData secp256k1SignToSignature(String rawData, BigInteger privateKey) { - ECKeyPair keyPair = ECKeyPair.create(privateKey); + ECKeyPair keyPair = GenCredential.createKeyPair(privateKey.toString(16)); return secp256k1SignToSignature(rawData, keyPair); } @@ -581,9 +602,7 @@ public static String secp256k1SigBase64Serialization( * @param signature signature base64 string * @return secp256k1 signature (v = 0,1) */ - public static SignatureData secp256k1SigBase64Deserialization( - String signature - ) { + public static SignatureData secp256k1SigBase64Deserialization(String signature) { byte[] sigBytes = base64Decode(signature.getBytes(StandardCharsets.UTF_8)); byte[] r = new byte[32]; byte[] s = new byte[32]; @@ -592,6 +611,25 @@ public static SignatureData secp256k1SigBase64Deserialization( return new SignatureData(sigBytes[64], r, s); } + /** + * De-Serialize secp256k1 signature base64 encoded string, in R, S, V (0, 1) format. + * + * @param signature signature base64 string + * @param publicKey publicKey + * @return secp256k1 signature (v = 0,1) + */ + public static SignatureData secp256k1SigBase64Deserialization( + String signature, + BigInteger publicKey) { + byte[] sigBytes = base64Decode(signature.getBytes(StandardCharsets.UTF_8)); + byte[] r = new byte[32]; + byte[] s = new byte[32]; + System.arraycopy(sigBytes, 0, r, 0, 32); + System.arraycopy(sigBytes, 32, s, 0, 32); + + return new SignatureData(sigBytes[64], r, s, Numeric.toBytesPadded(publicKey, 64)); + } + /** * Verify secp256k1 signature. * @@ -609,11 +647,19 @@ public static boolean verifySecp256k1Signature( if (rawData == null) { return false; } - SignatureData sigData = - secp256k1SigBase64Deserialization(signatureBase64); - ECDSASign ecdsaSign = new ECDSASign(); - byte[] hashBytes = Hash.sha3(rawData.getBytes()); - return ecdsaSign.secp256Verify(hashBytes, publicKey, sigData); + if (encryptType.equals(String.valueOf(EncryptType.ECDSA_TYPE))) { + SignatureData sigData = + secp256k1SigBase64Deserialization(signatureBase64); + byte[] hashBytes = Hash.sha3(rawData.getBytes()); + ECDSASign ecdsaSign = new ECDSASign(); + return ecdsaSign.secp256Verify(hashBytes, publicKey, sigData); + } else { + SM3Digest sm3Digest = new SM3Digest(); + byte[] hashBytes = sm3Digest.hash(rawData.getBytes()); + SignatureData sigData = + secp256k1SigBase64Deserialization(signatureBase64, publicKey); + return SM2Sign.verify(hashBytes, sigData); + } } catch (Exception e) { logger.error("Error occurred during secp256k1 sig verification: {}", e); return false; @@ -636,13 +682,20 @@ public static String recoverWeIdFromMsgAndSecp256Sig(String rawData, String sigB (byte) (sigData.getV() + 27), sigData.getR(), sigData.getS()); - ECDSASignature sig = - new ECDSASignature( - org.fisco.bcos.web3j.utils.Numeric.toBigInt(modifiedSigData.getR()), - org.fisco.bcos.web3j.utils.Numeric.toBigInt(modifiedSigData.getS())); - BigInteger k = Sign - .recoverFromSignature(modifiedSigData.getV() - 27, sig, hashBytes); - return WeIdUtils.convertPublicKeyToWeId(k.toString(10)); + + BigInteger publicKey; + if (encryptType.equals(String.valueOf(EncryptType.ECDSA_TYPE))) { + ECDSASignature sig = + new ECDSASignature( + org.fisco.bcos.web3j.utils.Numeric.toBigInt(modifiedSigData.getR()), + org.fisco.bcos.web3j.utils.Numeric.toBigInt(modifiedSigData.getS())); + publicKey = Sign + .recoverFromSignature(modifiedSigData.getV() - 27, sig, hashBytes); + } else { + // not support + throw new WeIdBaseException("not support!"); + } + return WeIdUtils.convertPublicKeyToWeId(publicKey.toString(10)); } /** @@ -703,7 +756,11 @@ public static byte[] decrypt(byte[] data, String privateKey) throws Exception { * @return publicKey */ public static BigInteger publicKeyFromPrivate(BigInteger privateKey) { - return Sign.publicKeyFromPrivate(privateKey); + if (encryptType.equals(String.valueOf(EncryptType.ECDSA_TYPE))) { + return Sign.publicKeyFromPrivate(privateKey); + } else { + return Sign.smPublicKeyFromPrivate(privateKey); + } } /** @@ -713,7 +770,11 @@ public static BigInteger publicKeyFromPrivate(BigInteger privateKey) { * @return WeIdPrivateKey */ public static ECKeyPair createKeyPairFromPrivate(BigInteger privateKey) { - return ECKeyPair.create(privateKey); + if (encryptType.equals(String.valueOf(EncryptType.ECDSA_TYPE))) { + return GenCredential.createECDSAKeyPair(privateKey.toString(16)); + } else { + return GenCredential.createGuomiKeyPair(privateKey.toString(16)); + } } /** diff --git a/src/main/java/com/webank/weid/util/OffLineBatchTask.java b/src/main/java/com/webank/weid/util/OffLineBatchTask.java index 116d5029c..341d1a3e5 100644 --- a/src/main/java/com/webank/weid/util/OffLineBatchTask.java +++ b/src/main/java/com/webank/weid/util/OffLineBatchTask.java @@ -9,7 +9,7 @@ import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.fisco.bcos.web3j.crypto.ECKeyPair; -import org.fisco.bcos.web3j.crypto.Keys; +import org.fisco.bcos.web3j.crypto.gm.GenCredential; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -49,7 +49,7 @@ public class OffLineBatchTask extends AbstractService { static { try { - ECKeyPair keyPair = Keys.createEcKeyPair(); + ECKeyPair keyPair = GenCredential.createKeyPair(); privateKey = String.valueOf(keyPair.getPrivateKey()); } catch (Exception e) { logger.error("Create weId failed.", e); diff --git a/src/main/java/com/webank/weid/util/WeIdUtils.java b/src/main/java/com/webank/weid/util/WeIdUtils.java index d7cbf46db..a06b71b47 100644 --- a/src/main/java/com/webank/weid/util/WeIdUtils.java +++ b/src/main/java/com/webank/weid/util/WeIdUtils.java @@ -143,7 +143,7 @@ public static boolean isPrivateKeyValid(WeIdPrivateKey weIdPrivateKey) { * @param publicKey the WeIdentity DID publicKey key * @return true if the private and publicKey key is match, false otherwise. */ - public static boolean isKeypairMatch(String privateKey, String publicKey) { + public static boolean isEcdsaKeypairMatch(String privateKey, String publicKey) { try { ECKeyPair keyPair = ECKeyPair.create(new BigInteger(privateKey)); return StringUtils.equals(String.valueOf(keyPair.getPublicKey()), publicKey); @@ -152,6 +152,18 @@ public static boolean isKeypairMatch(String privateKey, String publicKey) { } } + /** + * check if the public key matchs the private key. + * + * @param privateKey the WeIdentity DID private key + * @param publicKey the WeIdentity DID publicKey key + * @return true if the private and publicKey key is match, false otherwise. + */ + public static boolean isKeypairMatch(String privateKey, String publicKey) { + ECKeyPair keyPair = DataToolUtils.createKeyPairFromPrivate(new BigInteger(privateKey)); + return StringUtils.equals(String.valueOf(keyPair.getPublicKey()), publicKey); + } + /** * check if the given string is a valid address. * diff --git a/src/main/resources/fisco.properties.tpl b/src/main/resources/fisco.properties.tpl index 04741743a..c546afebd 100644 --- a/src/main/resources/fisco.properties.tpl +++ b/src/main/resources/fisco.properties.tpl @@ -47,6 +47,7 @@ web3sdk.keep-alive-seconds=60 ####################################################################################################### # Fisco-Bcos 2.x params, including Group ID and Encrypt Type group.id=1 +# Fisco-Bcos encrypt type, 0:ECDSA 1:SM2 encrypt.type=0 @@ -62,4 +63,11 @@ v1.client-key-store-path=client.keystore v1.key-store-password=123456 v2.ca-crt-path=ca.crt v2.node-crt-path=node.crt -v2.node-key-path=node.key \ No newline at end of file +v2.node-key-path=node.key + +# gm +gm.ca-crt-path=gmca.crt +gm.sdk-crt-path=gmsdk.crt +gm.sdk-key-path=gmsdk.key +gmen.sdk-crt-path=gmensdk.crt +gmen.sdk-key-path=gmensdk.key \ No newline at end of file diff --git a/src/test/java/com/webank/weid/full/TestBaseService.java b/src/test/java/com/webank/weid/full/TestBaseService.java index ec662b1d9..a6c46c561 100644 --- a/src/test/java/com/webank/weid/full/TestBaseService.java +++ b/src/test/java/com/webank/weid/full/TestBaseService.java @@ -46,8 +46,6 @@ import com.webank.weid.protocol.request.CreateWeIdArgs; import com.webank.weid.protocol.request.RegisterAuthorityIssuerArgs; import com.webank.weid.protocol.request.ServiceArgs; -import com.webank.weid.protocol.request.SetAuthenticationArgs; -import com.webank.weid.protocol.request.SetServiceArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; import com.webank.weid.protocol.response.ResponseData; import com.webank.weid.util.CredentialUtils; @@ -198,16 +196,12 @@ public abstract class TestBaseService extends BaseTest { @Override public synchronized void testInit() { - if (!isInitIssuer) { - try { - issuerPrivateList = new ArrayList(); - issuerPrivateList.add(privateKey); - initIssuer("org1.txt"); - isInitIssuer = true; - } catch (Exception e) { - logger.error("initIssuer error", e); - Assert.assertTrue(false); - } + try { + issuerPrivateList = new ArrayList(); + issuerPrivateList.add(privateKey); + } catch (Exception e) { + logger.error("initIssuer error", e); + Assert.assertTrue(false); } if (createWeIdResult == null) { @@ -254,16 +248,12 @@ public synchronized void testInit() { */ public synchronized void testInit4MlCpt() { - if (!isInitIssuer) { - try { - issuerPrivateList = new ArrayList(); - issuerPrivateList.add(privateKey); - initIssuer("org1.txt"); - //isInitIssuer = true; - } catch (Exception e) { - logger.error("initIssuer error", e); - Assert.assertTrue(false); - } + try { + issuerPrivateList = new ArrayList(); + issuerPrivateList.add(privateKey); + } catch (Exception e) { + logger.error("initIssuer error", e); + Assert.assertTrue(false); } if (createWeIdResult == null) { @@ -290,15 +280,12 @@ public synchronized void testInit4MlCpt() { */ public synchronized void testInit4MultiCpt() { - if (!isInitIssuer) { - try { - issuerPrivateList = new ArrayList(); - issuerPrivateList.add(privateKey); - initIssuer("org1.txt"); - } catch (Exception e) { - logger.error("initIssuer error", e); - Assert.assertTrue(false); - } + try { + issuerPrivateList = new ArrayList(); + issuerPrivateList.add(privateKey); + } catch (Exception e) { + logger.error("initIssuer error", e); + Assert.assertTrue(false); } if (createWeIdResult == null) { @@ -340,16 +327,12 @@ public synchronized void testInit4MultiCpt() { */ public synchronized void testInitSpecTplCpt() { - if (!isInitIssuer) { - try { - issuerPrivateList = new ArrayList(); - issuerPrivateList.add(privateKey); - initIssuer("org1.txt"); - //isInitIssuer = true; - } catch (Exception e) { - logger.error("initIssuer error", e); - Assert.assertTrue(false); - } + try { + issuerPrivateList = new ArrayList(); + issuerPrivateList.add(privateKey); + } catch (Exception e) { + logger.error("initIssuer error", e); + Assert.assertTrue(false); } if (createWeIdResult == null) { diff --git a/src/test/java/com/webank/weid/full/TestBaseUtil.java b/src/test/java/com/webank/weid/full/TestBaseUtil.java index 042f94def..fbc8be3cf 100644 --- a/src/test/java/com/webank/weid/full/TestBaseUtil.java +++ b/src/test/java/com/webank/weid/full/TestBaseUtil.java @@ -26,9 +26,6 @@ import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.StandardCharsets; -import java.security.InvalidAlgorithmParameterException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -38,12 +35,13 @@ import com.github.fge.jackson.JsonLoader; import org.apache.commons.lang3.StringUtils; import org.fisco.bcos.web3j.crypto.ECKeyPair; -import org.fisco.bcos.web3j.crypto.Keys; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import com.webank.weid.common.LogUtil; import com.webank.weid.common.PasswordKey; +import com.webank.weid.config.FiscoConfig; import com.webank.weid.constant.JsonSchemaConstant; import com.webank.weid.protocol.base.AuthorityIssuer; import com.webank.weid.protocol.base.CptBaseInfo; @@ -69,11 +67,20 @@ */ public class TestBaseUtil { + private static final FiscoConfig fiscoConfig; + /** * log4j. */ private static final Logger logger = LoggerFactory.getLogger(TestBaseUtil.class); + static { + logger.info("[init] begin init FiscoConfig."); + // load fisco.properties + fiscoConfig = new FiscoConfig(); + fiscoConfig.load(); + } + /** * build CreateCredentialArgs no cptId. */ @@ -631,22 +638,32 @@ public static PasswordKey createEcKeyPair() { PasswordKey passwordKey = new PasswordKey(); try { - ECKeyPair keyPair = Keys.createEcKeyPair(); + ECKeyPair keyPair = DataToolUtils.createKeyPair(); String publicKey = String.valueOf(keyPair.getPublicKey()); String privateKey = String.valueOf(keyPair.getPrivateKey()); passwordKey.setPrivateKey(privateKey); passwordKey.setPublicKey(publicKey); LogUtil.info(logger, "createEcKeyPair", passwordKey); - } catch (InvalidAlgorithmParameterException e) { - logger.error("createEcKeyPair error:", e); - } catch (NoSuchAlgorithmException e) { - logger.error("createEcKeyPair error:", e); - } catch (NoSuchProviderException e) { + } catch (Exception e) { logger.error("createEcKeyPair error:", e); } return passwordKey; } + /** + * create a new public key - private key. + * + * @return ECKeyPair + */ + public static ECKeyPair createKeyPair() { + try { + return DataToolUtils.createKeyPair(); + } catch (Exception e) { + logger.error("createEcKeyPair error:", e); + } + return null; + } + /** * to test the public and private key from the file. * @@ -743,7 +760,15 @@ public static String readPrivateKeyFromFile(String fileName) { InputStreamReader isr = null; StringBuffer privateKey = new StringBuffer(); - URL fileUrl = TestBaseUtil.class.getClassLoader().getResource(fileName); + URL fileUrl = null; + try { + PathMatchingResourcePatternResolver resolver = + new PathMatchingResourcePatternResolver(); + fileUrl = resolver.getResource("classpath:" + fileName).getFile().toURL(); + } catch (IOException e) { + e.printStackTrace(); + } + // URL fileUrl = TestBaseUtil.class.getClassLoader().getResource(fileName); if (fileUrl == null) { return privateKey.toString(); } diff --git a/src/test/java/com/webank/weid/full/auth/TestRegisterAuthorityIssuer.java b/src/test/java/com/webank/weid/full/auth/TestRegisterAuthorityIssuer.java index 51e98632c..dda8914be 100644 --- a/src/test/java/com/webank/weid/full/auth/TestRegisterAuthorityIssuer.java +++ b/src/test/java/com/webank/weid/full/auth/TestRegisterAuthorityIssuer.java @@ -782,7 +782,7 @@ public void testRegisterAuthorityIssuerCase17() { TestBaseUtil.buildRegisterAuthorityIssuerArgs(createWeIdResult, privateKey); registerAuthorityIssuerArgs.getAuthorityIssuer().setName( String.valueOf(System.currentTimeMillis())); - registerAuthorityIssuerArgs.getWeIdPrivateKey().setPrivateKey(issuerPrivateList.get(1)); + registerAuthorityIssuerArgs.getWeIdPrivateKey().setPrivateKey(issuerPrivateList.get(0)); ResponseData response = authorityIssuerService.registerAuthorityIssuer(registerAuthorityIssuerArgs); diff --git a/src/test/java/com/webank/weid/full/cpt/TestRegisterCptStringArgs.java b/src/test/java/com/webank/weid/full/cpt/TestRegisterCptStringArgs.java index 32f3534ab..c4ebf2b9b 100644 --- a/src/test/java/com/webank/weid/full/cpt/TestRegisterCptStringArgs.java +++ b/src/test/java/com/webank/weid/full/cpt/TestRegisterCptStringArgs.java @@ -26,7 +26,6 @@ public class TestRegisterCptStringArgs extends TestBaseService { @Override public synchronized void testInit() { - super.testInit(); if (createWeId == null) { createWeId = super.createWeId(); diff --git a/src/test/java/com/webank/weid/full/credentialpojo/TestCreateCredentialPojo.java b/src/test/java/com/webank/weid/full/credentialpojo/TestCreateCredentialPojo.java index c0cabad7c..afdcb70c4 100644 --- a/src/test/java/com/webank/weid/full/credentialpojo/TestCreateCredentialPojo.java +++ b/src/test/java/com/webank/weid/full/credentialpojo/TestCreateCredentialPojo.java @@ -322,10 +322,6 @@ public void testLiteCredentialPojo() { ResponseData resp = credentialPojoService.verify(liteCredential.getIssuer(), liteCredential); Assert.assertTrue(resp.getResult()); - String recovererdWeId = DataToolUtils.recoverWeIdFromMsgAndSecp256Sig( - CredentialPojoUtils.getLiteCredentialThumbprintWithoutSig(liteCredential), - liteCredential.getSignature()); - Assert.assertEquals(recovererdWeId, liteCredential.getIssuer()); // LiteCredential: // 1. getThumbprint() -> signature (针对凭证claim内容生成thumbprint,用私钥生成签名) @@ -965,7 +961,7 @@ public void testCreateAuthTokenAll() throws Exception { // Enforce a Register/Update system CPT first WeIdAuthentication sdkAuthen = new WeIdAuthentication(); - ECKeyPair keyPair = ECKeyPair.create(new BigInteger(privateKey)); + ECKeyPair keyPair = DataToolUtils.createKeyPairFromPrivate(new BigInteger(privateKey)); String keyWeId = WeIdUtils .convertAddressToWeId(new Address(Keys.getAddress(keyPair)).toString()); sdkAuthen.setWeId(keyWeId); diff --git a/src/test/java/com/webank/weid/full/weid/TestCreateWeId1.java b/src/test/java/com/webank/weid/full/weid/TestCreateWeId1.java index 8219b38fe..906ea571e 100644 --- a/src/test/java/com/webank/weid/full/weid/TestCreateWeId1.java +++ b/src/test/java/com/webank/weid/full/weid/TestCreateWeId1.java @@ -25,6 +25,7 @@ import mockit.MockUp; import org.fisco.bcos.web3j.crypto.ECKeyPair; import org.fisco.bcos.web3j.crypto.Keys; +import org.fisco.bcos.web3j.crypto.gm.GenCredential; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; @@ -75,28 +76,4 @@ public void testCreateWeId_doubleCreateSucess() { Assert.assertNotEquals(response.getResult().getWeId(), response1.getResult().getWeId()); } - /** - * case: Simulation throws an exception when calling the createEcKeyPair method. - */ - @Test - public void testCreateWeId_createEcKeyPairErr() { - - new MockUp() { - @Mock - public ECKeyPair createEcKeyPair() - throws NoSuchProviderException { - - throw new NoSuchProviderException(); - } - }; - - ResponseData response = weIdService.createWeId(); - LogUtil.info(logger, "createWeId", response); - - - Assert.assertEquals(ErrorCode.WEID_KEYPAIR_CREATE_FAILED.getCode(), - response.getErrorCode().intValue()); - Assert.assertNull(response.getResult()); - } - } diff --git a/src/test/java/com/webank/weid/full/weid/TestGetWeIdDocumentJson.java b/src/test/java/com/webank/weid/full/weid/TestGetWeIdDocumentJson.java index d2701efab..b6d43d4b2 100644 --- a/src/test/java/com/webank/weid/full/weid/TestGetWeIdDocumentJson.java +++ b/src/test/java/com/webank/weid/full/weid/TestGetWeIdDocumentJson.java @@ -36,7 +36,6 @@ import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.WeIdDocument; -import com.webank.weid.protocol.request.SetServiceArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; import com.webank.weid.protocol.response.ResponseData; diff --git a/src/test/java/com/webank/weid/full/weid/TestSetAuthentication.java b/src/test/java/com/webank/weid/full/weid/TestSetAuthentication.java index 8985df7a0..652255d2b 100644 --- a/src/test/java/com/webank/weid/full/weid/TestSetAuthentication.java +++ b/src/test/java/com/webank/weid/full/weid/TestSetAuthentication.java @@ -155,7 +155,7 @@ public void testSetAuthentication_weIdNotExist() { createWeIdResult.getUserWeIdPrivateKey()); LogUtil.info(logger, "setAuthentication", response); - Assert.assertEquals(ErrorCode.WEID_PRIVATEKEY_DOES_NOT_MATCH.getCode(), + Assert.assertEquals(ErrorCode.WEID_DOES_NOT_EXIST.getCode(), response.getErrorCode().intValue()); Assert.assertEquals(false, response.getResult()); } diff --git a/src/test/java/com/webank/weid/util/TestBuildPrivateKey.java b/src/test/java/com/webank/weid/util/TestBuildPrivateKey.java index d01dcf8a5..a5afbd389 100644 --- a/src/test/java/com/webank/weid/util/TestBuildPrivateKey.java +++ b/src/test/java/com/webank/weid/util/TestBuildPrivateKey.java @@ -22,7 +22,7 @@ import java.math.BigInteger; import org.junit.Assert; -import org.junit.Test; +import org.junit.Ignore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,7 +41,7 @@ public class TestBuildPrivateKey { /** * extract the private key in org1.txt and transform it into 16 binary system */ - @Test + @Ignore public void testBuildPrivateKey() { PasswordKey passwordKey = TestBaseUtil.resolvePk("org1.txt"); BigInteger bigInter1 = new BigInteger(passwordKey.getPrivateKey(), 10); diff --git a/src/test/java/com/webank/weid/util/TestCrypt.java b/src/test/java/com/webank/weid/util/TestCrypt.java index 3a4abde1a..0e2fc7003 100644 --- a/src/test/java/com/webank/weid/util/TestCrypt.java +++ b/src/test/java/com/webank/weid/util/TestCrypt.java @@ -20,13 +20,13 @@ package com.webank.weid.util; import org.fisco.bcos.web3j.crypto.ECKeyPair; -import org.fisco.bcos.web3j.crypto.Keys; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.webank.weid.full.TestBaseUtil; import com.webank.weid.suite.api.crypto.CryptoServiceFactory; import com.webank.weid.suite.api.crypto.params.Asymmetrickey; import com.webank.weid.suite.api.crypto.params.CryptoType; @@ -77,7 +77,7 @@ public void testRsa() throws Exception { public void testEcies_withPadding() throws Exception { // 外围有padding操作 for (int i = 0; i < 1000; i++) { - ECKeyPair keyPair = Keys.createEcKeyPair(); + ECKeyPair keyPair = TestBaseUtil.createKeyPair(); String publicKey = keyPair.getPublicKey().toString(); String privateKey = keyPair.getPrivateKey().toString(); String pubBase64 = KeyGenerator.decimalKeyToBase64(publicKey); @@ -101,7 +101,7 @@ public void testEcies_withPadding() throws Exception { public void testEcies_noPadding() throws Exception { // 外围没有padding操作 for (int i = 0; i < 1000; i++) { - ECKeyPair keyPair = Keys.createEcKeyPair(); + ECKeyPair keyPair = TestBaseUtil.createKeyPair(); String publicKey = keyPair.getPublicKey().toString(); String privateKey = keyPair.getPrivateKey().toString(); logger.info("pub key: {}", publicKey); @@ -121,7 +121,7 @@ public void testEcies_noPadding() throws Exception { @Test public void testDecimalKey() throws Exception { for (int i = 0; i < 1000; i++) { - ECKeyPair keyPair = Keys.createEcKeyPair(); + ECKeyPair keyPair = TestBaseUtil.createKeyPair(); String publicKey = keyPair.getPublicKey().toString(); String privateKey = keyPair.getPrivateKey().toString(); String pubBase64 = KeyGenerator.decimalKeyToBase64(publicKey); diff --git a/src/test/java/com/webank/weid/util/TestSignatureUtils.java b/src/test/java/com/webank/weid/util/TestSignatureUtils.java index 4a3ed5b5a..235c4b215 100644 --- a/src/test/java/com/webank/weid/util/TestSignatureUtils.java +++ b/src/test/java/com/webank/weid/util/TestSignatureUtils.java @@ -29,6 +29,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.webank.weid.full.TestBaseUtil; + /** * Test SignatureUtils. * @@ -47,8 +49,8 @@ public void testSignatureUtils() BigInteger publicKey = DataToolUtils.publicKeyFromPrivate(new BigInteger(privateKey)); logger.info("publicKey:{} ", publicKey); - ECKeyPair keyPair = DataToolUtils.createKeyPair(); - keyPair = DataToolUtils.createKeyPairFromPrivate(new BigInteger(privateKey)); + ECKeyPair keyPair = TestBaseUtil.createKeyPair(); + keyPair = ECKeyPair.create(new BigInteger(privateKey)); logger.info("publicKey:{} ", keyPair.getPublicKey()); logger.info("privateKey:{}", keyPair.getPrivateKey()); @@ -68,9 +70,8 @@ public void testSecp256k1Signatures() { String hexPrivKey = "58317564669857453586637110679746575832914889677346283755719850144028639639651"; String msg = "12345"; - org.fisco.bcos.web3j.crypto.ECKeyPair keyPair - = org.fisco.bcos.web3j.crypto.ECKeyPair.create(new BigInteger(hexPrivKey, 10)); - String sig = DataToolUtils.secp256k1Sign(msg, new BigInteger(hexPrivKey, 10)); + ECKeyPair keyPair = DataToolUtils.createKeyPairFromPrivate(new BigInteger(hexPrivKey)); + String sig = DataToolUtils.secp256k1Sign(msg, new BigInteger(hexPrivKey)); Boolean result = DataToolUtils.verifySecp256k1Signature(msg, sig, keyPair.getPublicKey()); Assert.assertTrue(result); } diff --git a/src/test/java/com/webank/weid/util/TestWeIdUtils.java b/src/test/java/com/webank/weid/util/TestWeIdUtils.java index c537b2de5..31cb375e7 100644 --- a/src/test/java/com/webank/weid/util/TestWeIdUtils.java +++ b/src/test/java/com/webank/weid/util/TestWeIdUtils.java @@ -94,11 +94,11 @@ public void testIsKeypairMatch() { + "76569372213582021586381145279900416808342958821437075568109344613716670953"; String privateKey = "58317564669857453586637110679746575832914889677346283755719850144028639639651"; - boolean result = WeIdUtils.isKeypairMatch(privateKey, publicKey); + boolean result = WeIdUtils.isEcdsaKeypairMatch(privateKey, publicKey); Assert.assertTrue(result); privateKey = "646467494548664"; - result = WeIdUtils.isKeypairMatch(privateKey, publicKey); + result = WeIdUtils.isEcdsaKeypairMatch(privateKey, publicKey); Assert.assertFalse(result); } From 0cf696511d7793c58b3c67df8d5f01dd3427fdeb Mon Sep 17 00:00:00 2001 From: yg3630536 <125480926@qq.com> Date: Thu, 14 Jan 2021 15:49:42 +0800 Subject: [PATCH 3/6] * get WeIdList by publicKey List --- .../java/com/webank/weid/rpc/WeIdService.java | 7 ++++++ .../weid/service/impl/WeIdServiceImpl.java | 17 ++++++++++++++ .../weid/full/weid/TestGetWeIdDocument.java | 22 +++++++++++++++++++ 3 files changed, 46 insertions(+) diff --git a/src/main/java/com/webank/weid/rpc/WeIdService.java b/src/main/java/com/webank/weid/rpc/WeIdService.java index 572e39ec6..72c49d587 100644 --- a/src/main/java/com/webank/weid/rpc/WeIdService.java +++ b/src/main/java/com/webank/weid/rpc/WeIdService.java @@ -219,4 +219,11 @@ ResponseData> getWeIdList( * @return total weid */ ResponseData getWeIdCount(); + + /** + * get WeID list by pubKey list. + * @param pubKeyList the pubKey list + * @return return the WeID list + */ + ResponseData> getWeIdListByPubKeyList(List pubKeyList); } diff --git a/src/main/java/com/webank/weid/service/impl/WeIdServiceImpl.java b/src/main/java/com/webank/weid/service/impl/WeIdServiceImpl.java index 6ffa86c0a..490f5109d 100644 --- a/src/main/java/com/webank/weid/service/impl/WeIdServiceImpl.java +++ b/src/main/java/com/webank/weid/service/impl/WeIdServiceImpl.java @@ -20,6 +20,7 @@ package com.webank.weid.service.impl; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -960,4 +961,20 @@ public ResponseData> getWeIdList( public ResponseData getWeIdCount() { return weIdServiceEngine.getWeIdCount(); } + + @Override + public ResponseData> getWeIdListByPubKeyList(List pubKeyList) { + if (pubKeyList == null || pubKeyList.size() == 0) { + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + List weIdList = new ArrayList(); + for (WeIdPublicKey weIdPublicKey : pubKeyList) { + if (weIdPublicKey != null && StringUtils.isNotBlank(weIdPublicKey.getPublicKey())) { + weIdList.add(WeIdUtils.convertPublicKeyToWeId(weIdPublicKey.getPublicKey())); + } else { + weIdList.add(StringUtils.EMPTY); + } + } + return new ResponseData<>(weIdList, ErrorCode.SUCCESS); + } } diff --git a/src/test/java/com/webank/weid/full/weid/TestGetWeIdDocument.java b/src/test/java/com/webank/weid/full/weid/TestGetWeIdDocument.java index 07b8be9d4..458934def 100644 --- a/src/test/java/com/webank/weid/full/weid/TestGetWeIdDocument.java +++ b/src/test/java/com/webank/weid/full/weid/TestGetWeIdDocument.java @@ -19,6 +19,9 @@ package com.webank.weid.full.weid; +import java.util.ArrayList; +import java.util.List; + import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Assert; import org.junit.Test; @@ -33,6 +36,7 @@ import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.WeIdDocument; import com.webank.weid.protocol.base.WeIdPrivateKey; +import com.webank.weid.protocol.base.WeIdPublicKey; import com.webank.weid.protocol.request.AuthenticationArgs; import com.webank.weid.protocol.request.PublicKeyArgs; import com.webank.weid.protocol.request.ServiceArgs; @@ -334,4 +338,22 @@ public void testGetWeIdDocument_weIdIsNull() { Assert.assertEquals(ErrorCode.WEID_INVALID.getCode(), weIdDoc.getErrorCode().intValue()); Assert.assertNull(weIdDoc.getResult()); } + + /** + * case: getWeIdList By publicKeyList. + */ + @Test + public void testGetWeIdListByPubkeyList() { + List pubKeyList = new ArrayList<>(); + int num = 5; + for (int i = 0; i < num; i++) { + WeIdPublicKey publicKey = new WeIdPublicKey(); + publicKey.setPublicKey(TestBaseUtil.createEcKeyPair().getPublicKey()); + pubKeyList.add(publicKey); + } + ResponseData> weIdListRes = weIdService.getWeIdListByPubKeyList(pubKeyList); + LogUtil.info(logger, "getWeIdListByPubKeyList", weIdListRes); + Assert.assertEquals(ErrorCode.SUCCESS.getCode(), weIdListRes.getErrorCode().intValue()); + Assert.assertEquals(num, weIdListRes.getResult().size()); + } } From c00d52a1d7de177c80f35410a7eb6a3cdff63707 Mon Sep 17 00:00:00 2001 From: yg3630536 <125480926@qq.com> Date: Thu, 21 Jan 2021 17:39:54 +0800 Subject: [PATCH 4/6] * fix the test for remove issuer --- .../webank/weid/full/auth/TestGetAllAuthorityIssuerList.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/webank/weid/full/auth/TestGetAllAuthorityIssuerList.java b/src/test/java/com/webank/weid/full/auth/TestGetAllAuthorityIssuerList.java index c8f817fb9..4c65ecb81 100644 --- a/src/test/java/com/webank/weid/full/auth/TestGetAllAuthorityIssuerList.java +++ b/src/test/java/com/webank/weid/full/auth/TestGetAllAuthorityIssuerList.java @@ -16,6 +16,7 @@ import com.webank.weid.protocol.request.RemoveAuthorityIssuerArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.util.DataToolUtils; public class TestGetAllAuthorityIssuerList extends TestBaseService { @@ -148,10 +149,10 @@ public void testGetAllAuthorityIssuerList_removeListThenQuery() { Assert.assertEquals(ErrorCode.SUCCESS.getCode(), response.getErrorCode().intValue()); List authorityIssuers = response.getResult(); - + String sdkWeId = DataToolUtils.convertPrivateKeyToDefaultWeId(privateKey); for (int i = 0; i < authorityIssuers.size(); i++) { String weId = authorityIssuers.get(i).getWeId(); - if (!weId.equals(createWeId.getWeId())) { + if (!weId.equals(createWeId.getWeId()) && !sdkWeId.equals(weId)) { RemoveAuthorityIssuerArgs removeAuthorityIssuerArgs = new RemoveAuthorityIssuerArgs(); removeAuthorityIssuerArgs.setWeId(weId); From 6f3f94a0f1e12394af4e132120610fd66a437e8b Mon Sep 17 00:00:00 2001 From: yg3630536 <125480926@qq.com> Date: Fri, 22 Jan 2021 11:23:42 +0800 Subject: [PATCH 5/6] * add cpt109 title and desc --- src/main/java/com/webank/weid/protocol/cpt/Cpt109.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/com/webank/weid/protocol/cpt/Cpt109.java b/src/main/java/com/webank/weid/protocol/cpt/Cpt109.java index 96bfebb05..2a0b18a1e 100644 --- a/src/main/java/com/webank/weid/protocol/cpt/Cpt109.java +++ b/src/main/java/com/webank/weid/protocol/cpt/Cpt109.java @@ -19,6 +19,8 @@ package com.webank.weid.protocol.cpt; +import com.github.reinert.jjschema.Attributes; + import lombok.Data; /** @@ -28,6 +30,8 @@ */ @Data +@Attributes(title = "Trusted Timestamp", + description = "Trusted Timestamp from authorized 3rd-party, or chain consensus") public class Cpt109 { /** From 25b4abd1a6eddad91d7cf5aca245d22c18b3496e Mon Sep 17 00:00:00 2001 From: yg3630536 <125480926@qq.com> Date: Mon, 25 Jan 2021 18:31:35 +0800 Subject: [PATCH 6/6] * fix the version and weid-contract-java * fix the function for getWeIDByPublickList --- VERSION | 2 +- build.gradle | 2 +- .../protocol/response/WeIdListResult.java | 17 ++++++++++ .../java/com/webank/weid/rpc/WeIdService.java | 5 +-- .../weid/service/impl/WeIdServiceImpl.java | 31 ++++++++++++++----- .../weid/full/weid/TestGetWeIdDocument.java | 5 +-- 6 files changed, 48 insertions(+), 14 deletions(-) create mode 100644 src/main/java/com/webank/weid/protocol/response/WeIdListResult.java diff --git a/VERSION b/VERSION index 081af9a10..afa2b3515 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.7.1 \ No newline at end of file +1.8.0 \ No newline at end of file diff --git a/build.gradle b/build.gradle index 8a7353b9f..dd8f2844f 100644 --- a/build.gradle +++ b/build.gradle @@ -153,7 +153,7 @@ dependencies { localDeps 'org.projectlombok:lombok:1.18.10' if (!gradle.startParameter.isOffline()) { compile logger, lombok, apache_commons, json, mysql_driver, redisson, zxing, rpc, pdfbox, protobuf, caffeine, oval - compile("com.webank:weid-contract-java:1.2.29-rc.2-SNAPSHOT") { + compile("com.webank:weid-contract-java:1.2.29") { exclude group: "org.slf4j", module: "slf4j-log4j12" } compile fileTree(dir: 'lib', include: '*.jar') diff --git a/src/main/java/com/webank/weid/protocol/response/WeIdListResult.java b/src/main/java/com/webank/weid/protocol/response/WeIdListResult.java new file mode 100644 index 000000000..e11504d62 --- /dev/null +++ b/src/main/java/com/webank/weid/protocol/response/WeIdListResult.java @@ -0,0 +1,17 @@ +package com.webank.weid.protocol.response; + +import java.util.List; + +import lombok.Data; + +/** + * get WeId and errorCode by pubkeyList response. + * + */ +@Data +public class WeIdListResult { + + private List weIdList; + + private List errorCodeList; +} diff --git a/src/main/java/com/webank/weid/rpc/WeIdService.java b/src/main/java/com/webank/weid/rpc/WeIdService.java index 72c49d587..7877ae47b 100644 --- a/src/main/java/com/webank/weid/rpc/WeIdService.java +++ b/src/main/java/com/webank/weid/rpc/WeIdService.java @@ -32,6 +32,7 @@ import com.webank.weid.protocol.request.ServiceArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.protocol.response.WeIdListResult; /** @@ -223,7 +224,7 @@ ResponseData> getWeIdList( /** * get WeID list by pubKey list. * @param pubKeyList the pubKey list - * @return return the WeID list + * @return return the WeIDListResult */ - ResponseData> getWeIdListByPubKeyList(List pubKeyList); + ResponseData getWeIdListByPubKeyList(List pubKeyList); } diff --git a/src/main/java/com/webank/weid/service/impl/WeIdServiceImpl.java b/src/main/java/com/webank/weid/service/impl/WeIdServiceImpl.java index 490f5109d..23b04ae65 100644 --- a/src/main/java/com/webank/weid/service/impl/WeIdServiceImpl.java +++ b/src/main/java/com/webank/weid/service/impl/WeIdServiceImpl.java @@ -25,6 +25,7 @@ import java.util.Objects; import com.fasterxml.jackson.databind.ObjectMapper; + import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.fisco.bcos.web3j.crypto.ECKeyPair; @@ -48,6 +49,7 @@ import com.webank.weid.protocol.request.ServiceArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.protocol.response.WeIdListResult; import com.webank.weid.rpc.WeIdService; import com.webank.weid.util.DataToolUtils; import com.webank.weid.util.WeIdUtils; @@ -963,18 +965,31 @@ public ResponseData getWeIdCount() { } @Override - public ResponseData> getWeIdListByPubKeyList(List pubKeyList) { + public ResponseData getWeIdListByPubKeyList(List pubKeyList) { if (pubKeyList == null || pubKeyList.size() == 0) { return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); } - List weIdList = new ArrayList(); - for (WeIdPublicKey weIdPublicKey : pubKeyList) { - if (weIdPublicKey != null && StringUtils.isNotBlank(weIdPublicKey.getPublicKey())) { - weIdList.add(WeIdUtils.convertPublicKeyToWeId(weIdPublicKey.getPublicKey())); + WeIdListResult weIdListResult = new WeIdListResult(); + weIdListResult.setWeIdList(new ArrayList<>()); + weIdListResult.setErrorCodeList(new ArrayList<>()); + ResponseData responseData = new ResponseData(); + pubKeyList.forEach(weIdPublicKey -> { + String weId = WeIdUtils.convertPublicKeyToWeId(weIdPublicKey.getPublicKey()); + if (StringUtils.isBlank(weId)) { + weIdListResult.getWeIdList().add(null); + weIdListResult.getErrorCodeList().add(ErrorCode.WEID_PUBLICKEY_INVALID.getCode()); } else { - weIdList.add(StringUtils.EMPTY); + if (this.isWeIdExist(weId).getResult()) { + weIdListResult.getWeIdList().add(weId); + weIdListResult.getErrorCodeList().add(ErrorCode.SUCCESS.getCode()); + } else { + weIdListResult.getWeIdList().add(null); + weIdListResult.getErrorCodeList().add( + ErrorCode.WEID_PUBLIC_KEY_NOT_EXIST.getCode()); + } } - } - return new ResponseData<>(weIdList, ErrorCode.SUCCESS); + }); + responseData.setResult(weIdListResult); + return responseData; } } diff --git a/src/test/java/com/webank/weid/full/weid/TestGetWeIdDocument.java b/src/test/java/com/webank/weid/full/weid/TestGetWeIdDocument.java index 458934def..2e2aea3a3 100644 --- a/src/test/java/com/webank/weid/full/weid/TestGetWeIdDocument.java +++ b/src/test/java/com/webank/weid/full/weid/TestGetWeIdDocument.java @@ -42,6 +42,7 @@ import com.webank.weid.protocol.request.ServiceArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.protocol.response.WeIdListResult; /** * getWeIdDocument method for testing WeIdService. @@ -351,9 +352,9 @@ public void testGetWeIdListByPubkeyList() { publicKey.setPublicKey(TestBaseUtil.createEcKeyPair().getPublicKey()); pubKeyList.add(publicKey); } - ResponseData> weIdListRes = weIdService.getWeIdListByPubKeyList(pubKeyList); + ResponseData weIdListRes = weIdService.getWeIdListByPubKeyList(pubKeyList); LogUtil.info(logger, "getWeIdListByPubKeyList", weIdListRes); Assert.assertEquals(ErrorCode.SUCCESS.getCode(), weIdListRes.getErrorCode().intValue()); - Assert.assertEquals(num, weIdListRes.getResult().size()); + Assert.assertEquals(num, weIdListRes.getResult().getWeIdList().size()); } }