diff --git a/.ci/script/build-ci.sh b/.ci/script/build-ci.sh index f644da276..8449832f7 100644 --- a/.ci/script/build-ci.sh +++ b/.ci/script/build-ci.sh @@ -122,7 +122,7 @@ function deploy_contract() echo "contract deployment done." } -function install_font() +function install_font() { # download NotoSansCJKtc-Regular.ttf if [ ! -f NotoSansCJKtc-Regular.ttf ]; then diff --git a/VERSION b/VERSION index 60fdb8d5d..9dbb0c005 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.6.7 \ No newline at end of file +1.7.0 \ No newline at end of file diff --git a/build.gradle b/build.gradle index a0428c0a9..2119dcc1e 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.26") { + compile("com.webank:weid-contract-java:1.2.27") { exclude group: "org.slf4j", module: "slf4j-log4j12" } compile fileTree(dir: 'lib', include: '*.jar') diff --git a/src/main/java/com/webank/weid/constant/CnsType.java b/src/main/java/com/webank/weid/constant/CnsType.java index d5d263e3e..4f919f371 100644 --- a/src/main/java/com/webank/weid/constant/CnsType.java +++ b/src/main/java/com/webank/weid/constant/CnsType.java @@ -34,17 +34,17 @@ public enum CnsType { /** * 默认的cns定义,此cns用于weid主合约存储. */ - DEFAULT("allOrg", "v2.1"), + DEFAULT("allOrg", "v3.1"), /** * 共享cns定义,此cns可作为机构共享数据存储. */ - SHARE("share", "v2.1"), + SHARE("share", "v3.1"), /** * 机构配置CNS定义. */ - ORG_CONFING("orgConfig", "v2.1"); + ORG_CONFING("orgConfig", "v3.1"); private static final String SPLIT_CHAR = "/"; diff --git a/src/main/java/com/webank/weid/constant/ErrorCode.java b/src/main/java/com/webank/weid/constant/ErrorCode.java index 1ddd03c9b..e35cd5d7e 100644 --- a/src/main/java/com/webank/weid/constant/ErrorCode.java +++ b/src/main/java/com/webank/weid/constant/ErrorCode.java @@ -345,10 +345,15 @@ public enum ErrorCode { CREDENTIAL_EVIDENCE_HASH_MISMATCH(100501, "evidence hash mismatch"), /** - * The credential evidence hash mismatch. + * The credential evidence does not exist on chain. */ CREDENTIAL_EVIDENCE_NOT_EXIST(100502, "evidence does not exist on chain"), + /** + * The credential evidence already exists on chain. + */ + CREDENTIAL_EVIDENCE_ALREADY_EXISTS(100503, "evidence already exists on chain"), + /** * The credential evidence interface does not support fisco bcos 1.3. */ diff --git a/src/main/java/com/webank/weid/constant/WeIdConstant.java b/src/main/java/com/webank/weid/constant/WeIdConstant.java index db23fba07..b1ef08fe9 100644 --- a/src/main/java/com/webank/weid/constant/WeIdConstant.java +++ b/src/main/java/com/webank/weid/constant/WeIdConstant.java @@ -234,7 +234,17 @@ public final class WeIdConstant { * Removed WeID authentication specified tag. */ public static final String REMOVED_AUTHENTICATION_TAG = "OBSOLETEAUTH"; - + + /** + * Evidence Revoke attribute key. + */ + public static final String EVIDENCE_REVOKE_KEY = "revoke"; + + /** + * Evidence Un-Revoke attribute key. + */ + public static final String EVIDENCE_UNREVOKE_KEY = "unrevoke"; + /** * the address key in bucket. */ @@ -258,6 +268,9 @@ public final class WeIdConstant { public static final Integer ADD_PUBKEY_FAILURE_CODE = -1; + public static final Integer CPT_DATA_INDEX = 0; + public static final Integer POLICY_DATA_INDEX = 1; + public static final Long RECOGNIZED_AUTHORITY_ISSUER_FLAG = 1L; public static enum PublicKeyType { diff --git a/src/main/java/com/webank/weid/contract/deploy/DeployContract.java b/src/main/java/com/webank/weid/contract/deploy/DeployContract.java index b66d25705..9db6859c9 100644 --- a/src/main/java/com/webank/weid/contract/deploy/DeployContract.java +++ b/src/main/java/com/webank/weid/contract/deploy/DeployContract.java @@ -26,7 +26,6 @@ import com.webank.weid.config.FiscoConfig; import com.webank.weid.constant.ErrorCode; import com.webank.weid.constant.WeIdConstant; -import com.webank.weid.contract.deploy.v1.DeployContractV1; import com.webank.weid.contract.deploy.v2.DeployContractV2; import com.webank.weid.exception.WeIdBaseException; @@ -86,7 +85,7 @@ public static void main(String[] args) { public static void deployContract(String privateKey, boolean instantEnable) { if (fiscoConfig.getVersion().startsWith(WeIdConstant.FISCO_BCOS_1_X_VERSION_PREFIX)) { - DeployContractV1.deployContract(privateKey); + throw new WeIdBaseException(ErrorCode.THIS_IS_UNSUPPORTED); } else { DeployContractV2.deployContract(privateKey, fiscoConfig, instantEnable); } diff --git a/src/main/java/com/webank/weid/contract/deploy/v1/DeployContractV1.java b/src/main/java/com/webank/weid/contract/deploy/v1/DeployContractV1.java deleted file mode 100644 index 90e56861a..000000000 --- a/src/main/java/com/webank/weid/contract/deploy/v1/DeployContractV1.java +++ /dev/null @@ -1,430 +0,0 @@ -/* - * Copyright© (2018-2019) WeBank Co., Ltd. - * - * This file is part of weid-java-sdk. - * - * weid-java-sdk is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * weid-java-sdk is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with weid-java-sdk. If not, see . - */ - -package com.webank.weid.contract.deploy.v1; - -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import org.apache.commons.lang3.StringUtils; -import org.bcos.web3j.abi.datatypes.Address; -import org.bcos.web3j.crypto.Credentials; -import org.bcos.web3j.crypto.GenCredential; -import org.bcos.web3j.protocol.Web3j; -import org.bcos.web3j.protocol.core.methods.response.TransactionReceipt; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.webank.weid.constant.WeIdConstant; -import com.webank.weid.contract.deploy.AddressProcess; -import com.webank.weid.contract.v1.AuthorityIssuerController; -import com.webank.weid.contract.v1.AuthorityIssuerData; -import com.webank.weid.contract.v1.CommitteeMemberController; -import com.webank.weid.contract.v1.CommitteeMemberData; -import com.webank.weid.contract.v1.CptController; -import com.webank.weid.contract.v1.CptData; -import com.webank.weid.contract.v1.EvidenceContract; -import com.webank.weid.contract.v1.EvidenceFactory; -import com.webank.weid.contract.v1.RoleController; -import com.webank.weid.contract.v1.SpecificIssuerController; -import com.webank.weid.contract.v1.SpecificIssuerData; -import com.webank.weid.contract.v1.WeIdContract; -import com.webank.weid.service.BaseService; -import com.webank.weid.util.WeIdUtils; - -/** - * The Class DeployContract. - * - * @author tonychen - */ -public class DeployContractV1 extends AddressProcess { - - /** - * log4j. - */ - private static final Logger logger = LoggerFactory.getLogger(DeployContractV1.class); - - /** - * The Constant for default deploy contracts timeout. - */ - private static final Integer DEFAULT_DEPLOY_CONTRACTS_TIMEOUT_IN_SECONDS = 15; - - /** - * The credentials. - */ - private static Credentials credentials; - - /** - * web3j object. - */ - private static Web3j web3j; - - /** - * Inits the credentials. - * - * @return true, if successful - */ - private static boolean initCredentials(String inputPrivateKey) { - if (StringUtils.isNotBlank(inputPrivateKey)) { - logger.info("[DeployContractV1] begin to init credentials by privateKey.."); - credentials = GenCredential.create(new BigInteger(inputPrivateKey).toString(16)); - } else { - logger.info("[DeployContractV1] begin to init credentials.."); - credentials = GenCredential.create(); - } - - if (credentials == null) { - logger.error("[DeployContractV1] credentials init failed. "); - return false; - } - String publicKey = credentials.getEcKeyPair().getPublicKey().toString(); - String privateKey = credentials.getEcKeyPair().getPrivateKey().toString(); - writeAddressToFile(publicKey, "ecdsa_key.pub"); - writeAddressToFile(privateKey, "ecdsa_key"); - return true; - } - - /** - * Inits the web3j. - */ - protected static void initWeb3j() { - if (web3j == null) { - web3j = (Web3j) BaseService.getWeb3j(); - } - } - - /** - * depoly contract on FISCO BCOS 1.3.x. - * @param privateKey the private key - */ - public static void deployContract(String privateKey) { - initWeb3j(); - initCredentials(privateKey); - String weIdContractAddress = deployWeIdContract(); - String roleControllerAddress = deployRoleControllerContracts(); - Map addrList = deployIssuerContracts(roleControllerAddress); - if (addrList.containsKey("AuthorityIssuerData")) { - String authorityIssuerDataAddress = addrList.get("AuthorityIssuerData"); - deployCptContracts( - authorityIssuerDataAddress, - weIdContractAddress, - roleControllerAddress - ); - } - deployEvidenceContractsNew(); - } - - private static String deployWeIdContract() { - if (web3j == null) { - initWeb3j(); - } - Future f = - WeIdContract.deploy( - web3j, - credentials, - WeIdConstant.GAS_PRICE, - WeIdConstant.GAS_LIMIT, - WeIdConstant.INILITIAL_VALUE); - - try { - WeIdContract weIdContract = - f.get(DEFAULT_DEPLOY_CONTRACTS_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS); - String contractAddress = weIdContract.getContractAddress(); - writeAddressToFile(contractAddress, "weIdContract.address"); - return contractAddress; - } catch (InterruptedException | ExecutionException | TimeoutException e) { - logger.error("WeIdContract deploy exception", e); - } - return StringUtils.EMPTY; - } - - private static String deployCptContracts( - String authorityIssuerDataAddress, - String weIdContractAddress, - String roleControllerAddress) { - if (web3j == null) { - initWeb3j(); - } - - try { - Future f1 = - CptData.deploy( - web3j, - credentials, - WeIdConstant.GAS_PRICE, - WeIdConstant.GAS_LIMIT, - WeIdConstant.INILITIAL_VALUE, - new Address(authorityIssuerDataAddress)); - CptData cptData = f1.get(DEFAULT_DEPLOY_CONTRACTS_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS); - String cptDataAddress = cptData.getContractAddress(); - - Future f2 = - CptController.deploy( - web3j, - credentials, - WeIdConstant.GAS_PRICE, - WeIdConstant.GAS_LIMIT, - WeIdConstant.INILITIAL_VALUE, - new Address(cptDataAddress), - new Address(weIdContractAddress) - ); - CptController cptController = - f2.get(DEFAULT_DEPLOY_CONTRACTS_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS); - String cptControllerAddress = cptController.getContractAddress(); - writeAddressToFile(cptControllerAddress, "cptController.address"); - - Future f3 = cptController - .setRoleController(new Address(roleControllerAddress)); - f3.get(DEFAULT_DEPLOY_CONTRACTS_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS); - } catch (InterruptedException | ExecutionException | TimeoutException e) { - logger.error("CptController deploy exception", e); - } - - return StringUtils.EMPTY; - } - - private static String deployRoleControllerContracts() { - if (web3j == null) { - initWeb3j(); - } - - try { - Future f1 = - RoleController.deploy( - web3j, - credentials, - WeIdConstant.GAS_PRICE, - WeIdConstant.GAS_LIMIT, - WeIdConstant.INILITIAL_VALUE); - RoleController roleController = - f1.get(DEFAULT_DEPLOY_CONTRACTS_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS); - return roleController.getContractAddress(); - } catch (InterruptedException | ExecutionException | TimeoutException e) { - logger.error("RoleController deploy exception", e); - return StringUtils.EMPTY; - } - } - - private static Map deployIssuerContracts(String roleControllerAddress) { - if (web3j == null) { - initWeb3j(); - } - Map issuerAddressList = new HashMap<>(); - - Future f2; - String committeeMemberDataAddress; - try { - f2 = CommitteeMemberData.deploy( - web3j, - credentials, - WeIdConstant.GAS_PRICE, - WeIdConstant.GAS_LIMIT, - WeIdConstant.INILITIAL_VALUE, - new Address(roleControllerAddress)); - CommitteeMemberData committeeMemberData = - f2.get(DEFAULT_DEPLOY_CONTRACTS_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS); - committeeMemberDataAddress = committeeMemberData.getContractAddress(); - if (!WeIdUtils.isEmptyAddress(new Address(committeeMemberDataAddress))) { - issuerAddressList.put("CommitteeMemberData", committeeMemberDataAddress); - } - } catch (Exception e) { - logger.error("CommitteeMemberData deployment error:", e); - return issuerAddressList; - } - - Future f3; - String committeeMemberControllerAddress; - try { - f3 = CommitteeMemberController.deploy( - web3j, - credentials, - WeIdConstant.GAS_PRICE, - WeIdConstant.GAS_LIMIT, - WeIdConstant.INILITIAL_VALUE, - new Address(committeeMemberDataAddress), - new Address(roleControllerAddress) - ); - CommitteeMemberController committeeMemberController = - f3.get(DEFAULT_DEPLOY_CONTRACTS_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS); - committeeMemberControllerAddress = committeeMemberController.getContractAddress(); - if (!WeIdUtils.isEmptyAddress(new Address(committeeMemberControllerAddress))) { - issuerAddressList - .put("CommitteeMemberController", committeeMemberControllerAddress); - } - } catch (Exception e) { - logger.error("CommitteeMemberController deployment error:", e); - return issuerAddressList; - } - - Future f4; - String authorityIssuerDataAddress; - try { - f4 = AuthorityIssuerData.deploy( - web3j, - credentials, - WeIdConstant.GAS_PRICE, - WeIdConstant.GAS_LIMIT, - WeIdConstant.INILITIAL_VALUE, - new Address(roleControllerAddress) - ); - AuthorityIssuerData authorityIssuerData = - f4.get(DEFAULT_DEPLOY_CONTRACTS_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS); - authorityIssuerDataAddress = authorityIssuerData.getContractAddress(); - if (!WeIdUtils.isEmptyAddress(new Address(authorityIssuerDataAddress))) { - issuerAddressList.put("AuthorityIssuerData", authorityIssuerDataAddress); - } - } catch (Exception e) { - logger.error("AuthorityIssuerData deployment error:", e); - return issuerAddressList; - } - - Future f5; - String authorityIssuerControllerAddress; - try { - f5 = AuthorityIssuerController.deploy( - web3j, - credentials, - WeIdConstant.GAS_PRICE, - WeIdConstant.GAS_LIMIT, - WeIdConstant.INILITIAL_VALUE, - new Address(authorityIssuerDataAddress), - new Address(roleControllerAddress)); - AuthorityIssuerController authorityIssuerController = - f5.get(DEFAULT_DEPLOY_CONTRACTS_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS); - authorityIssuerControllerAddress = authorityIssuerController.getContractAddress(); - if (!WeIdUtils.isEmptyAddress(new Address(authorityIssuerControllerAddress))) { - issuerAddressList - .put("AuthorityIssuerController", authorityIssuerControllerAddress); - } - } catch (Exception e) { - logger.error("AuthorityIssuerController deployment error:", e); - return issuerAddressList; - } - - try { - writeAddressToFile(authorityIssuerControllerAddress, "authorityIssuer.address"); - } catch (Exception e) { - logger.error("Write error:", e); - } - - String specificIssuerDataAddress = StringUtils.EMPTY; - try { - Future f6 = SpecificIssuerData.deploy( - web3j, - credentials, - WeIdConstant.GAS_PRICE, - WeIdConstant.GAS_LIMIT, - WeIdConstant.INILITIAL_VALUE - ); - SpecificIssuerData specificIssuerData = f6.get( - DEFAULT_DEPLOY_CONTRACTS_TIMEOUT_IN_SECONDS, - TimeUnit.SECONDS - ); - specificIssuerDataAddress = specificIssuerData.getContractAddress(); - if (!WeIdUtils.isEmptyAddress(new Address(specificIssuerDataAddress))) { - issuerAddressList.put("SpecificIssuerData", specificIssuerDataAddress); - } - } catch (Exception e) { - logger.error("SpecificIssuerData deployment error:", e); - } - - try { - Future f7 = SpecificIssuerController.deploy( - web3j, - credentials, - WeIdConstant.GAS_PRICE, - WeIdConstant.GAS_LIMIT, - WeIdConstant.INILITIAL_VALUE, - new Address(specificIssuerDataAddress), - new Address(roleControllerAddress) - ); - SpecificIssuerController specificIssuerController = f7.get( - DEFAULT_DEPLOY_CONTRACTS_TIMEOUT_IN_SECONDS, - TimeUnit.SECONDS - ); - String specificIssuerControllerAddress = specificIssuerController.getContractAddress(); - if (!WeIdUtils.isEmptyAddress(new Address(specificIssuerControllerAddress))) { - issuerAddressList.put("SpecificIssuerController", specificIssuerControllerAddress); - } - try { - writeAddressToFile(specificIssuerControllerAddress, "specificIssuer.address"); - } catch (Exception e) { - logger.error("Write error:", e); - } - } catch (Exception e) { - logger.error("SpecificIssuerController deployment error:", e); - } - return issuerAddressList; - } - - @Deprecated - private static String deployEvidenceContracts() { - if (web3j == null) { - initWeb3j(); - } - - try { - Future f = - EvidenceFactory.deploy( - web3j, - credentials, - WeIdConstant.GAS_PRICE, - WeIdConstant.GAS_LIMIT, - WeIdConstant.INILITIAL_VALUE - ); - EvidenceFactory evidenceFactory = f - .get(DEFAULT_DEPLOY_CONTRACTS_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS); - String evidenceFactoryAddress = evidenceFactory.getContractAddress(); - writeAddressToFile(evidenceFactoryAddress, "evidenceController.address"); - return evidenceFactoryAddress; - } catch (InterruptedException | ExecutionException | TimeoutException e) { - logger.error("EvidenceFactory deploy exception", e); - } - return StringUtils.EMPTY; - } - - private static String deployEvidenceContractsNew() { - if (web3j == null) { - initWeb3j(); - } - try { - Future f = - EvidenceContract.deploy( - web3j, - credentials, - WeIdConstant.GAS_PRICE, - WeIdConstant.GAS_LIMIT, - WeIdConstant.INILITIAL_VALUE - ); - EvidenceContract evidenceContract = f - .get(DEFAULT_DEPLOY_CONTRACTS_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS); - String evidenceContractAddress = evidenceContract.getContractAddress(); - writeAddressToFile(evidenceContractAddress, "evidenceController.address"); - return evidenceContractAddress; - } catch (Exception e) { - logger.error("EvidenceFactory deploy exception", e); - } - return StringUtils.EMPTY; - } -} diff --git a/src/main/java/com/webank/weid/contract/deploy/v2/DeployContractV2.java b/src/main/java/com/webank/weid/contract/deploy/v2/DeployContractV2.java index 67f02bd13..ee3caab98 100644 --- a/src/main/java/com/webank/weid/contract/deploy/v2/DeployContractV2.java +++ b/src/main/java/com/webank/weid/contract/deploy/v2/DeployContractV2.java @@ -213,6 +213,14 @@ private static String deployCptContracts( authorityIssuerDataAddress).send(); String cptDataAddress = cptData.getContractAddress(); + CptData policyData = + CptData.deploy( + web3j, + credentials, + new StaticGasProvider(WeIdConstant.GAS_PRICE, WeIdConstant.GAS_LIMIT), + authorityIssuerDataAddress).send(); + String policyDataAddress = policyData.getContractAddress(); + CptController cptController = CptController.deploy( web3j, @@ -227,7 +235,11 @@ private static String deployCptContracts( TransactionReceipt receipt = cptController.setRoleController(roleControllerAddress).send(); if (receipt == null) { - logger.error("CptController deploy exception"); + logger.error("CptController deploy exception: role address illegal"); + } + receipt = cptController.setPolicyData(policyDataAddress).send(); + if (receipt == null) { + logger.error("CptController deploy exception: policy data address illegal"); } } catch (Exception e) { logger.error("CptController deploy exception", e); diff --git a/src/main/java/com/webank/weid/contract/deploy/v2/RegisterAddressV2.java b/src/main/java/com/webank/weid/contract/deploy/v2/RegisterAddressV2.java index b065605e0..8fe3d04db 100644 --- a/src/main/java/com/webank/weid/contract/deploy/v2/RegisterAddressV2.java +++ b/src/main/java/com/webank/weid/contract/deploy/v2/RegisterAddressV2.java @@ -133,7 +133,7 @@ private static String deployBucket(String privateKey) throws Exception { */ public static boolean enableHash(CnsType cnsType, String hash, WeIdPrivateKey weIdPrivateKey) { logger.info("[enableHash] enable hash on chain."); - boolean result = getBucket(cnsType).enableHash(hash, weIdPrivateKey).getResult(); + boolean result = getBucket(cnsType).enable(hash, weIdPrivateKey).getResult(); logger.info("[enableHash] the result of enable. result = {}", result); return result; } diff --git a/src/main/java/com/webank/weid/protocol/amop/GetTransDataArgs.java b/src/main/java/com/webank/weid/protocol/amop/GetTransDataArgs.java index 7f8f69e78..bd533ea94 100644 --- a/src/main/java/com/webank/weid/protocol/amop/GetTransDataArgs.java +++ b/src/main/java/com/webank/weid/protocol/amop/GetTransDataArgs.java @@ -25,7 +25,6 @@ import lombok.Setter; import lombok.ToString; -import com.webank.weid.constant.ServiceType; import com.webank.weid.protocol.amop.base.AmopBaseMsgArgs; /** diff --git a/src/main/java/com/webank/weid/protocol/base/ClaimPolicyBaseInfo.java b/src/main/java/com/webank/weid/protocol/base/ClaimPolicyBaseInfo.java new file mode 100644 index 000000000..c0c113a06 --- /dev/null +++ b/src/main/java/com/webank/weid/protocol/base/ClaimPolicyBaseInfo.java @@ -0,0 +1,41 @@ +/* + * Copyright© (2018) WeBank Co., Ltd. + * + * This file is part of weid-java-sdk. + * + * weid-java-sdk is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * weid-java-sdk is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with weid-java-sdk. If not, see . + */ + +package com.webank.weid.protocol.base; + +import lombok.Data; + +/** + * The base data structure for the SDK API register CPT info. + * + * @author junqizhang + */ +@Data +public class ClaimPolicyBaseInfo { + + /** + * Required: The id for the CPT. + */ + private Integer claimPolicyId; + + /** + * Required: The version of the CPT for the same CPT id. + */ + private Integer claimPolicyVersion; +} diff --git a/src/main/java/com/webank/weid/protocol/base/Cpt.java b/src/main/java/com/webank/weid/protocol/base/Cpt.java index 82f237d2d..75af9c5fe 100644 --- a/src/main/java/com/webank/weid/protocol/base/Cpt.java +++ b/src/main/java/com/webank/weid/protocol/base/Cpt.java @@ -26,7 +26,7 @@ /** * The base data structure for the CPT. * - * @author lingfenghe + * @author junqizhang */ @Data public class Cpt { diff --git a/src/main/java/com/webank/weid/protocol/base/EndpointInfo.java b/src/main/java/com/webank/weid/protocol/base/EndpointInfo.java index 1ca664240..b860286d5 100644 --- a/src/main/java/com/webank/weid/protocol/base/EndpointInfo.java +++ b/src/main/java/com/webank/weid/protocol/base/EndpointInfo.java @@ -23,7 +23,6 @@ import java.util.List; import lombok.Data; -import org.apache.commons.lang3.StringUtils; /** * An EndpointInfo contains a requestName with an N:1 relationship - N in, 1 requestName. SDK diff --git a/src/main/java/com/webank/weid/protocol/base/EvidenceSignInfo.java b/src/main/java/com/webank/weid/protocol/base/EvidenceSignInfo.java index e0447266a..0c56f3464 100644 --- a/src/main/java/com/webank/weid/protocol/base/EvidenceSignInfo.java +++ b/src/main/java/com/webank/weid/protocol/base/EvidenceSignInfo.java @@ -48,4 +48,10 @@ public class EvidenceSignInfo { * The extra value this signer records on chain. */ private List logs = new ArrayList<>(); + + /** + * Whether this signer revoked this evidence. This is initialized as null, and will be set + * appropriate values upon getEvidence(). + */ + private Boolean revoked = null; } diff --git a/src/main/java/com/webank/weid/protocol/base/PresentationPolicyE.java b/src/main/java/com/webank/weid/protocol/base/PresentationPolicyE.java index 2a78ef13e..cf4f89eb4 100644 --- a/src/main/java/com/webank/weid/protocol/base/PresentationPolicyE.java +++ b/src/main/java/com/webank/weid/protocol/base/PresentationPolicyE.java @@ -82,12 +82,6 @@ public class PresentationPolicyE extends Version implements JsonSerializer { */ private String policyType = "original"; - /** - * close the constructor. - */ - private PresentationPolicyE() { - } - /** * create the PresentationPolicyE with policyFileName, * please make sure the JSON file in your classPath. diff --git a/src/main/java/com/webank/weid/protocol/response/RsvSignature.java b/src/main/java/com/webank/weid/protocol/response/RsvSignature.java index af023af6f..4b9ca8331 100644 --- a/src/main/java/com/webank/weid/protocol/response/RsvSignature.java +++ b/src/main/java/com/webank/weid/protocol/response/RsvSignature.java @@ -21,8 +21,8 @@ import lombok.Data; -import org.bcos.web3j.abi.datatypes.generated.Bytes32; -import org.bcos.web3j.abi.datatypes.generated.Uint8; +import org.fisco.bcos.web3j.abi.datatypes.generated.Bytes32; +import org.fisco.bcos.web3j.abi.datatypes.generated.Uint8; /** * The internal base RSV signature data class. diff --git a/src/main/java/com/webank/weid/protocol/response/TransactionInfo.java b/src/main/java/com/webank/weid/protocol/response/TransactionInfo.java index 21d65d84d..f6c020ea4 100644 --- a/src/main/java/com/webank/weid/protocol/response/TransactionInfo.java +++ b/src/main/java/com/webank/weid/protocol/response/TransactionInfo.java @@ -22,7 +22,7 @@ import java.math.BigInteger; import lombok.Data; -import org.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; /** * The basic transaction information. Caller can further use these information to track the detailed @@ -62,20 +62,6 @@ public TransactionInfo(TransactionReceipt receipt) { } } - /** - * Constructor from a transactionReceipt. - * - * @param receipt the transaction receipt - */ - public TransactionInfo( - org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt receipt) { - if (receipt != null) { - this.blockNumber = receipt.getBlockNumber(); - this.transactionHash = receipt.getTransactionHash(); - this.transactionIndex = receipt.getTransactionIndex(); - } - } - /** * Constructor. * diff --git a/src/main/java/com/webank/weid/rpc/EvidenceService.java b/src/main/java/com/webank/weid/rpc/EvidenceService.java index eea4aad18..1aedd5e8a 100644 --- a/src/main/java/com/webank/weid/rpc/EvidenceService.java +++ b/src/main/java/com/webank/weid/rpc/EvidenceService.java @@ -22,6 +22,7 @@ import com.webank.weid.protocol.base.CredentialPojo; import com.webank.weid.protocol.base.EvidenceInfo; import com.webank.weid.protocol.base.HashString; +import com.webank.weid.protocol.base.WeIdAuthentication; import com.webank.weid.protocol.base.WeIdPrivateKey; import com.webank.weid.protocol.inf.Hashable; import com.webank.weid.protocol.response.ResponseData; @@ -37,14 +38,29 @@ public interface EvidenceService { * Create a new evidence to blockchain, and return the evidence's hash value on-chain. Supports * following types of input: Credential, CredentialWrapper, CredentialPojo, plain hash String, * After a successful creation, the hash value will be recorded onto blockchain, and this hash - * value can be used as key to lookup on blockchain. + * value can be used as key to lookup on blockchain. This will fail if evidence already exists. * * @param object the given Java object * @param weIdPrivateKey the signer WeID's private key - * @return evidence hash value. Return empty string if failed due to any reason. + * @return evidence hash value. Return empty string if failed, e.g. already existed. */ ResponseData createEvidence(Hashable object, WeIdPrivateKey weIdPrivateKey); + /** + * Create a new evidence to blockchain and return the hash value, with appending log. This will + * fail if evidence already exists. + * + * @param object the given Java object + * @param log appendable log entry - can be null or empty + * @param weIdAuthentication weid authentication (only checks private key) + * @return evidence hash value. Return empty string if failed, e.g. already existed. + */ + ResponseData createEvidenceWithLog( + Hashable object, + String log, + WeIdAuthentication weIdAuthentication + ); + /** * Create a new evidence together with log and custom key. Other guys can use this custom key, * OR its hash value, to lookup the detailed information of this evidence. Multiple calls of @@ -52,7 +68,7 @@ public interface EvidenceService { * * @param object the given Java object * @param weIdPrivateKey the signer WeID's private key - * @param log log entry + * @param log appendable log entry - can be null or empty * @param customKey custom key determined by creator - it cannot be a hash value though * @return evidence hash value */ @@ -64,11 +80,12 @@ ResponseData createEvidenceWithLogAndCustomKey( ); /** - * Add log entry for an existing evidence. This log will be recorded on blockchain permanently, - * and finally it will be fetched as a list when trying to get evidence. + * Add log entry for an existing evidence, appending on existing log entries. This log will be + * recorded on blockchain permanently, and finally it will be fetched as a list when trying to + * get evidence. Log must not be empty. * * @param hashValue hash value - * @param log log entry - can be null or empty + * @param log Not null log entry * @param weIdPrivateKey the signer WeID's private key * @return true if succeeded, false otherwise */ @@ -79,20 +96,83 @@ ResponseData addLogByHash( ); /** - * Add log entry for an existing evidence. This log will be recorded on blockchain permanently, - * and finally it will be fetched as a list when trying to get evidence. + * Add signature and log as a new signer to an existing evidence, appending on existing log + * entries. Log must not be empty. The signer might be different than the existing signers. * + * @param hashValue hash value + * @param log Not null log entry + * @param weIdPrivateKey the signer WeID's private key + * @return true if succeeded, false otherwise + */ + ResponseData addSignatureAndLogByHash( + String hashValue, + String log, + WeIdPrivateKey weIdPrivateKey + ); + + /** + * Add log entry for an existing evidence, appending on existing log entries. This log will be + * recorded on blockchain permanently, and finally it will be fetched as a list when trying to + * get evidence. Log must not be empty. It will firstly try to fetch the hash value given the + * custom key, and if the hash value does not exist, it will use the supplementing hash value + * (1st parameter) to make up. + * + * @param hashValueSupplement the hash value supplement if the custom key does not exist * @param customKey custom key - * @param log log entry - can be null or empty + * @param log Not null log entry * @param weIdPrivateKey the signer WeID's private key * @return true if succeeded, false otherwise */ ResponseData addLogByCustomKey( + String hashValueSupplement, + String customKey, + String log, + WeIdPrivateKey weIdPrivateKey + ); + + /** + * Add signature and log as a new signer to an existing evidence. Log can be empty. + * + * @param hashValueSupplement the hash value supplement if the custom key does not exist + * @param customKey custom key + * @param log Not null log entry + * @param weIdPrivateKey the signer WeID's private key + * @return true if succeeded, false otherwise + */ + ResponseData addSignatureAndLogByCustomKey( + String hashValueSupplement, String customKey, String log, WeIdPrivateKey weIdPrivateKey ); + /** + * Revoke an evidence - which can be un-revoked. + * + * @param object the object + * @param weIdAuthentication the weid authentication + * @return true if yes, false otherwise, with error codes + */ + ResponseData revoke(Hashable object, WeIdAuthentication weIdAuthentication); + + /** + * Un-revoke an evidence. + * + * @param object the object + * @param weIdAuthentication the weid authentication + * @return true if yes, false otherwise, with error codes + */ + ResponseData unRevoke(Hashable object, WeIdAuthentication weIdAuthentication); + + /** + * Check whether this evidence is revoked by this WeID. + * + * @param evidenceInfo the EvidenceInfo + * @param weId the signer WeID + * @return true if revoked, false otherwise + */ + ResponseData isRevoked(EvidenceInfo evidenceInfo, String weId); + /** * Get the evidence info from blockchain using hash as key. * diff --git a/src/main/java/com/webank/weid/rpc/PolicyService.java b/src/main/java/com/webank/weid/rpc/PolicyService.java new file mode 100644 index 000000000..c4e22912a --- /dev/null +++ b/src/main/java/com/webank/weid/rpc/PolicyService.java @@ -0,0 +1,89 @@ +/* + * Copyright© (2018-2019) WeBank Co., Ltd. + * + * This file is part of weid-java-sdk. + * + * weid-java-sdk is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * weid-java-sdk is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with weid-java-sdk. If not, see . + */ + +package com.webank.weid.rpc; + +import java.util.List; + +import com.webank.weid.protocol.base.ClaimPolicy; +import com.webank.weid.protocol.base.PresentationPolicyE; +import com.webank.weid.protocol.base.WeIdAuthentication; +import com.webank.weid.protocol.response.ResponseData; + +/** + * Service inf for operation on Policy on blockchain (Claim protocol Type). + * + * @author junqizhang 2020.8 + */ +public interface PolicyService { + + /** + * Register Claim Policy on blockchain and assign it under a CPT ID. + * + * @param cptId CPT ID + * @param policyJson Policy Json file + * @param weIdAuthentication WeID auth + * @return claimPolicyId the Claim policy ID on-chain + */ + ResponseData registerClaimPolicy(Integer cptId, String policyJson, + WeIdAuthentication weIdAuthentication); + + /** + * Get Claim Policy Json from blockchain given a policy ID. + * + * @param policyId the Claim Policy ID on-chain + * @return the claim Json + */ + ResponseData getClaimPolicy(Integer policyId); + + /** + * Get all claim policies from this CPT ID. + * + * @param cptId cpt id + * @return claim policies list + */ + ResponseData> getClaimPoliciesFromCpt(Integer cptId); + + /** + * Register Presentation Policy which contains a number of claim policies. + * + * @param claimPolicyIdList claim policies list + * @param weIdAuthentication weid auth + * @return the presentation policy id + */ + ResponseData registerPresentationPolicy(List claimPolicyIdList, + WeIdAuthentication weIdAuthentication); + + /** + * Get Presentation policies under this id from chain. + * + * @param presentationPolicyId presentation policy id + * @return the full presentation policy + */ + ResponseData getPresentationPolicy(Integer presentationPolicyId); + + /** + * Get all claim policies from chain. + * + * @param startPos start position + * @param num batch number + * @return claim policy list + */ + ResponseData> getAllClaimPolicies(Integer startPos, Integer num); +} diff --git a/src/main/java/com/webank/weid/rpc/WeIdService.java b/src/main/java/com/webank/weid/rpc/WeIdService.java index f5fdf66dd..572e39ec6 100644 --- a/src/main/java/com/webank/weid/rpc/WeIdService.java +++ b/src/main/java/com/webank/weid/rpc/WeIdService.java @@ -212,4 +212,11 @@ ResponseData> getWeIdList( Integer indexInBlock, boolean direction ); + + /** + * get total weId. + * + * @return total weid + */ + ResponseData getWeIdCount(); } diff --git a/src/main/java/com/webank/weid/rpc/callback/OnNotifyCallbackV1.java b/src/main/java/com/webank/weid/rpc/callback/OnNotifyCallbackV1.java deleted file mode 100644 index e6f65877b..000000000 --- a/src/main/java/com/webank/weid/rpc/callback/OnNotifyCallbackV1.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright© (2018-2019) WeBank Co., Ltd. - * - * This file is part of weid-java-sdk. - * - * weid-java-sdk is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * weid-java-sdk is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with weid-java-sdk. If not, see . - */ - -package com.webank.weid.rpc.callback; - -import java.util.HashMap; -import java.util.Map; - -import org.bcos.channel.client.ChannelPushCallback; -import org.bcos.channel.dto.ChannelPush; -import org.bcos.channel.dto.ChannelResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.webank.weid.constant.AmopMsgType; -import com.webank.weid.protocol.amop.AmopRequestBody; -import com.webank.weid.util.DataToolUtils; - -/** - * Created by junqizhang on 08/07/2017. - */ -public class OnNotifyCallbackV1 extends ChannelPushCallback implements RegistCallBack { - - private static final Logger logger = LoggerFactory.getLogger(OnNotifyCallbackV1.class); - - private Map amopCallBackMap = new HashMap(); - - private AmopCallback defaultAmopCallback = new AmopCallback(); - - public void registAmopCallback(Integer msgType, AmopCallback routeCallBack) { - amopCallBackMap.put(msgType, routeCallBack); - } - - public AmopCallback getAmopCallback(Integer msgType) { - return amopCallBackMap.get(msgType); - } - - @Override - public void onPush(ChannelPush push) { - - logger.info("received ChannelPush v1 msg : " + push.getContent()); - if (0 == amopCallBackMap.size()) { - ChannelResponse response = new ChannelResponse(); - response.setContent("directRouteCallback is null on server side!"); - response.setErrorCode(0); - push.sendResponse(response); - return; - } - - AmopRequestBody amopRequestBody = - DataToolUtils.deserialize(push.getContent(), AmopRequestBody.class); - AmopMsgType msgType = amopRequestBody.getMsgType(); - AmopCallback amopCallBack = amopCallBackMap.get(msgType.getValue()); - if (amopCallBack == null) { - amopCallBack = defaultAmopCallback; - } - String messageBody = amopRequestBody.getMsgBody(); - String result = null; - try { - result = msgType.callOnPush(amopCallBack, push.getMessageID(), messageBody); - } catch (Exception e) { - logger.error("callOnPush error, please check the log.", e); - } - - /* - * 接收到以后需要给发送端回包 - */ - ChannelResponse response = new ChannelResponse(); - response.setContent(result); - response.setErrorCode(0); - push.sendResponse(response); - } -} diff --git a/src/main/java/com/webank/weid/service/fisco/WeServer.java b/src/main/java/com/webank/weid/service/fisco/WeServer.java index d8427fdb7..403b24766 100644 --- a/src/main/java/com/webank/weid/service/fisco/WeServer.java +++ b/src/main/java/com/webank/weid/service/fisco/WeServer.java @@ -33,11 +33,9 @@ import com.webank.weid.config.FiscoConfig; import com.webank.weid.constant.AmopMsgType; import com.webank.weid.constant.CnsType; -import com.webank.weid.constant.WeIdConstant; import com.webank.weid.exception.WeIdBaseException; import com.webank.weid.protocol.response.AmopResponse; import com.webank.weid.rpc.callback.RegistCallBack; -import com.webank.weid.service.fisco.v1.WeServerV1; import com.webank.weid.service.fisco.v2.WeServerV2; import com.webank.weid.service.impl.base.AmopCommonArgs; import com.webank.weid.service.impl.callback.CommonCallback; @@ -111,12 +109,7 @@ public static synchronized WeServer getInstance( synchronized (WeServer.class) { weServer = weServerContext.get(groupId); if (weServer == null) { - if (fiscoConfig.getVersion() - .startsWith(WeIdConstant.FISCO_BCOS_1_X_VERSION_PREFIX)) { - weServer = new WeServerV1(fiscoConfig); - } else { - weServer = new WeServerV2(fiscoConfig); - } + weServer = new WeServerV2(fiscoConfig); weServer.initWeb3j(groupId); weServerContext.put(groupId, weServer); } diff --git a/src/main/java/com/webank/weid/service/fisco/v1/WeServerV1.java b/src/main/java/com/webank/weid/service/fisco/v1/WeServerV1.java deleted file mode 100644 index dd63aa905..000000000 --- a/src/main/java/com/webank/weid/service/fisco/v1/WeServerV1.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright© (2018-2019) WeBank Co., Ltd. - * - * This file is part of weid-java-sdk. - * - * weid-java-sdk is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * weid-java-sdk is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with weid-java-sdk. If not, see . - */ - -package com.webank.weid.service.fisco.v1; - -import java.io.IOException; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; - -import org.bcos.channel.client.ChannelPushCallback; -import org.bcos.channel.client.Service; -import org.bcos.channel.dto.ChannelRequest; -import org.bcos.channel.dto.ChannelResponse; -import org.bcos.channel.handler.ChannelConnections; -import org.bcos.web3j.crypto.Credentials; -import org.bcos.web3j.crypto.ECKeyPair; -import org.bcos.web3j.crypto.GenCredential; -import org.bcos.web3j.protocol.Web3j; -import org.bcos.web3j.protocol.channel.ChannelEthereumService; -import org.bcos.web3j.protocol.core.Response; -import org.bcos.web3j.protocol.core.methods.response.EthBlockNumber; -import org.fisco.bcos.web3j.precompile.cns.CnsInfo; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.webank.weid.config.FiscoConfig; -import com.webank.weid.constant.CnsType; -import com.webank.weid.exception.InitWeb3jException; -import com.webank.weid.exception.PrivateKeyIllegalException; -import com.webank.weid.exception.WeIdBaseException; -import com.webank.weid.protocol.response.AmopResponse; -import com.webank.weid.rpc.callback.OnNotifyCallbackV1; -import com.webank.weid.service.fisco.WeServer; -import com.webank.weid.service.impl.base.AmopCommonArgs; - -public final class WeServerV1 extends WeServer { - - private static final Logger logger = LoggerFactory.getLogger(WeServerV1.class); - - private Web3j web3j; - private Service service; - private Credentials credentials; - - public WeServerV1(FiscoConfig fiscoConfig) { - super(fiscoConfig, new OnNotifyCallbackV1()); - } - - @Override - public Web3j getWeb3j() { - return web3j; - } - - @Override - public Service getService() { - return service; - } - - @Override - public Credentials getCredentials() { - return credentials; - } - - @Override - protected void initWeb3j(Integer groupId) { - logger.info("[WeServiceImplV1] begin to init web3j instance.."); - service = buildFiscoBcosService(fiscoConfig); - service.setPushCallback((ChannelPushCallback) pushCallBack); - // Set topics for AMOP - service.setTopics(new ArrayList<>(super.getTopic())); - try { - service.run(); - } catch (Exception e) { - logger.error("[WeServiceImplV1] Service init failed. ", e); - throw new InitWeb3jException(e); - } - - ChannelEthereumService channelEthereumService = new ChannelEthereumService(); - channelEthereumService.setChannelService(service); - web3j = Web3j.build(channelEthereumService); - if (web3j == null) { - logger.error("[WeServiceImplV1] web3j init failed."); - throw new InitWeb3jException("web3j init failed."); - } - - credentials = GenCredential.create(); - if (credentials == null) { - logger.error("[WeServiceImplV1] credentials init failed."); - throw new InitWeb3jException("credentials init failed."); - } - logger.info("[WeServiceImplV1] init web3j instance success.."); - } - - private Service buildFiscoBcosService(FiscoConfig fiscoConfig) { - - Service service = new Service(); - service.setOrgID(fiscoConfig.getCurrentOrgId()); - service.setConnectSeconds(Integer.valueOf(fiscoConfig.getWeb3sdkTimeout())); - - // connection params - ChannelConnections channelConnections = new ChannelConnections(); - channelConnections.setCaCertPath("classpath:" + fiscoConfig.getV1CaCrtPath()); - channelConnections.setClientCertPassWord(fiscoConfig.getV1ClientCrtPassword()); - channelConnections - .setClientKeystorePath("classpath:" + fiscoConfig.getV1ClientKeyStorePath()); - channelConnections.setKeystorePassWord(fiscoConfig.getV1KeyStorePassword()); - channelConnections.setConnectionsStr(processNodes(fiscoConfig.getNodes())); - ConcurrentHashMap allChannelConnections = - new ConcurrentHashMap<>(); - allChannelConnections.put(fiscoConfig.getCurrentOrgId(), channelConnections); - service.setAllChannelConnections(allChannelConnections); - - // thread pool params - service.setThreadPool(super.initializePool(Integer.parseInt(fiscoConfig.getGroupId()))); - return service; - } - - private List processNodes(String nodes) { - List listTmp = Arrays.asList(nodes.split(",")); - List nodeList = new ArrayList(); - for (String node : listTmp) { - if (node.indexOf("@") == -1) { - node = "WeIdentity@" + node; - } - nodeList.add(node); - } - return nodeList; - } - - @Override - public Credentials createCredentials(String privateKey) { - Credentials credentials; - try { - ECKeyPair keyPair = ECKeyPair.create(new BigInteger(privateKey)); - credentials = Credentials.create(keyPair); - return credentials; - } catch (Exception e) { - throw new PrivateKeyIllegalException(e); - } - } - - @Override - public AmopResponse sendChannelMessage(AmopCommonArgs amopCommonArgs, int timeOut) { - - ChannelRequest request = new ChannelRequest(); - request.setTimeout(super.getTimeOut(timeOut)); - request.setToTopic(amopCommonArgs.getToAmopId()); - request.setMessageID(amopCommonArgs.getMessageId()); - request.setContent(amopCommonArgs.getMessage()); - - ChannelResponse response = this.getService().sendChannelMessage2(request); - - AmopResponse amopResponse = new AmopResponse(); - amopResponse.setMessageId(response.getMessageID()); - amopResponse.setErrorCode(response.getErrorCode()); - amopResponse.setResult(response.getContent()); - amopResponse.setErrorMessage(response.getErrorMessage()); - return amopResponse; - } - - @Override - public int getBlockNumber() throws IOException { - Response response = getWeb3j().ethBlockNumber().send(); - if (response instanceof EthBlockNumber) { - EthBlockNumber ethBlockNumber = (EthBlockNumber) response; - return ethBlockNumber.getBlockNumber().intValue(); - } - return 0; - } - - @Override - public Class getWeb3jClass() { - return Web3j.class; - } - - @Override - public String getVersion() throws IOException { - return this.getWeb3j().web3ClientVersion().send().getResult(); - } - - @Override - protected CnsInfo queryCnsInfo(CnsType cnsType) throws WeIdBaseException { - return null; - } -} 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 0bca4aba6..68bd0990c 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,7 +24,6 @@ import java.util.List; import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; import org.fisco.bcos.channel.client.ChannelPushCallback; import org.fisco.bcos.channel.client.Service; import org.fisco.bcos.channel.dto.ChannelRequest; 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 09e3fcdc2..0e865dcf7 100644 --- a/src/main/java/com/webank/weid/service/impl/CptServiceImpl.java +++ b/src/main/java/com/webank/weid/service/impl/CptServiceImpl.java @@ -19,12 +19,13 @@ package com.webank.weid.service.impl; +import java.math.BigInteger; import java.util.HashMap; import java.util.Map; import com.webank.wedpr.selectivedisclosure.CredentialTemplateEntity; import org.apache.commons.lang3.StringUtils; -import org.bcos.web3j.crypto.Sign.SignatureData; +import org.fisco.bcos.web3j.crypto.Sign.SignatureData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -136,14 +137,14 @@ public ResponseData registerCpt(CptMapArgs args, Integer cptId) { String weId = args.getWeIdAuthentication().getWeId(); WeIdPrivateKey weIdPrivateKey = args.getWeIdAuthentication().getWeIdPrivateKey(); - String cptJsonSchemaNew = this.cptSchemaToString(args); + String cptJsonSchemaNew = DataToolUtils.cptSchemaToString(args); RsvSignature rsvSignature = sign( weId, cptJsonSchemaNew, weIdPrivateKey); String address = WeIdUtils.convertWeIdToAddress(weId); return cptServiceEngine.registerCpt(cptId, address, cptJsonSchemaNew, rsvSignature, - weIdPrivateKey.getPrivateKey()); + weIdPrivateKey.getPrivateKey(), WeIdConstant.CPT_DATA_INDEX); } catch (Exception e) { logger.error("[registerCpt] register cpt failed due to unknown error. ", e); return new ResponseData<>(null, ErrorCode.UNKNOW_ERROR); @@ -175,14 +176,14 @@ public ResponseData registerCpt(CptMapArgs args) { String weId = args.getWeIdAuthentication().getWeId(); WeIdPrivateKey weIdPrivateKey = args.getWeIdAuthentication().getWeIdPrivateKey(); - String cptJsonSchemaNew = this.cptSchemaToString(args); + String cptJsonSchemaNew = DataToolUtils.cptSchemaToString(args); RsvSignature rsvSignature = sign( weId, cptJsonSchemaNew, weIdPrivateKey); String address = WeIdUtils.convertWeIdToAddress(weId); return cptServiceEngine.registerCpt(address, cptJsonSchemaNew, rsvSignature, - weIdPrivateKey.getPrivateKey()); + weIdPrivateKey.getPrivateKey(), WeIdConstant.CPT_DATA_INDEX); } catch (Exception e) { logger.error("[registerCpt] register cpt failed due to unknown error. ", e); return new ResponseData<>(null, ErrorCode.UNKNOW_ERROR); @@ -204,7 +205,7 @@ public ResponseData queryCpt(Integer cptId) { String cptIdStr = String.valueOf(cptId); ResponseData result = cptCahceNode.get(cptIdStr); if (result == null) { - result = cptServiceEngine.queryCpt(cptId); + result = cptServiceEngine.queryCpt(cptId, WeIdConstant.CPT_DATA_INDEX); if (result.getErrorCode().intValue() == ErrorCode.SUCCESS.getCode()) { cptCahceNode.put(cptIdStr, result); } @@ -270,7 +271,7 @@ public ResponseData updateCpt(CptMapArgs args, Integer cptId) { String weId = args.getWeIdAuthentication().getWeId(); WeIdPrivateKey weIdPrivateKey = args.getWeIdAuthentication().getWeIdPrivateKey(); - String cptJsonSchemaNew = this.cptSchemaToString(args); + String cptJsonSchemaNew = DataToolUtils.cptSchemaToString(args); RsvSignature rsvSignature = sign( weId, cptJsonSchemaNew, @@ -281,7 +282,8 @@ public ResponseData updateCpt(CptMapArgs args, Integer cptId) { address, cptJsonSchemaNew, rsvSignature, - weIdPrivateKey.getPrivateKey()); + weIdPrivateKey.getPrivateKey(), + WeIdConstant.CPT_DATA_INDEX); if (result.getErrorCode().intValue() == ErrorCode.SUCCESS.getCode()) { cptCahceNode.remove(String.valueOf(cptId)); } @@ -302,8 +304,8 @@ private RsvSignature sign( sb.append(cptPublisher); sb.append(WeIdConstant.PIPELINE); sb.append(jsonSchema); - SignatureData signatureData = - DataToolUtils.signMessage(sb.toString(), cptPublisherPrivateKey.getPrivateKey()); + SignatureData signatureData = DataToolUtils.secp256k1SignToSignature( + sb.toString(), new BigInteger(cptPublisherPrivateKey.getPrivateKey())); return DataToolUtils.convertSignatureDataToRsv(signatureData); } @@ -362,23 +364,7 @@ private ErrorCode validateCptJsonSchemaMap( return ErrorCode.SUCCESS; } - /** - * create new cpt json schema. - * - * @param cptJsonSchema Map - * @return String - */ - private String cptSchemaToString(CptMapArgs args) throws Exception { - - Map cptJsonSchema = args.getCptJsonSchema(); - Map cptJsonSchemaNew = new HashMap(); - cptJsonSchemaNew.put(JsonSchemaConstant.SCHEMA_KEY, JsonSchemaConstant.SCHEMA_VALUE); - cptJsonSchemaNew.put(JsonSchemaConstant.TYPE_KEY, JsonSchemaConstant.DATA_TYPE_OBJECT); - cptJsonSchemaNew.putAll(cptJsonSchema); - String cptType = args.getCptType().getName(); - cptJsonSchemaNew.put(CredentialConstant.CPT_TYPE_KEY, cptType); - return DataToolUtils.serialize(cptJsonSchemaNew); - } + /* (non-Javadoc) * @see com.webank.weid.rpc.CptService#queryCredentialTemplate(java.lang.Integer) 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 7535bc8b1..40dae7978 100644 --- a/src/main/java/com/webank/weid/service/impl/CredentialPojoServiceImpl.java +++ b/src/main/java/com/webank/weid/service/impl/CredentialPojoServiceImpl.java @@ -41,9 +41,9 @@ import com.webank.wedpr.selectivedisclosure.proto.VerificationRule; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; -import org.bcos.web3j.abi.datatypes.Address; -import org.bcos.web3j.crypto.ECKeyPair; -import org.bcos.web3j.crypto.Keys; +import org.fisco.bcos.web3j.abi.datatypes.Address; +import org.fisco.bcos.web3j.crypto.ECKeyPair; +import org.fisco.bcos.web3j.crypto.Keys; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -659,20 +659,13 @@ private static ErrorCode verifySingleSignedCredential( WeIdDocument weIdDocument = innerResponseData.getResult(); errorCode = DataToolUtils.verifySecp256k1SignatureFromWeId( rawData, credential.getSignature(), weIdDocument, weIdPublicKeyId); - if (errorCode != ErrorCode.SUCCESS && errorCode - != ErrorCode.CREDENTIAL_VERIFY_SUCCEEDED_WITH_WRONG_PUBLIC_KEY_ID) { - return DataToolUtils.verifySignatureFromWeId( - rawData, credential.getSignature(), weIdDocument, weIdPublicKeyId); - } return errorCode; } } else { boolean result; try { result = DataToolUtils.verifySecp256k1Signature(rawData, - credential.getSignature(), new BigInteger(publicKey)) || DataToolUtils - .verifySignature(rawData, - credential.getSignature(), new BigInteger(publicKey)); + credential.getSignature(), new BigInteger(publicKey)); } catch (Exception e) { logger.error("[verifyContent] verify signature fail.", e); @@ -1625,15 +1618,7 @@ private ErrorCode checkInputArgs( .verifySecp256k1SignatureFromWeId(presentationE.toRawData(), signature, weIdDocument, null); if (errorCode.getCode() != ErrorCode.SUCCESS.getCode()) { - errorCode = DataToolUtils - .verifySignatureFromWeId(presentationE.toRawData(), signature, weIdDocument, null); - if (errorCode.getCode() != ErrorCode.SUCCESS.getCode()) { - logger.error( - "[verify] verify presentation signature failed, error message : {}.", - errorCode.getCodeDesc() - ); - return ErrorCode.PRESENTATION_SIGNATURE_MISMATCH; - } + return ErrorCode.PRESENTATION_SIGNATURE_MISMATCH; } return ErrorCode.SUCCESS; } 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 4a1e5170e..cae6fb346 100644 --- a/src/main/java/com/webank/weid/service/impl/CredentialServiceImpl.java +++ b/src/main/java/com/webank/weid/service/impl/CredentialServiceImpl.java @@ -21,7 +21,6 @@ import java.math.BigInteger; import java.nio.charset.StandardCharsets; -import java.security.SignatureException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -30,10 +29,10 @@ import com.github.fge.jsonschema.core.report.ProcessingReport; import org.apache.commons.lang3.StringUtils; -import org.bcos.web3j.abi.datatypes.Address; -import org.bcos.web3j.crypto.ECKeyPair; -import org.bcos.web3j.crypto.Keys; -import org.bcos.web3j.crypto.Sign; +import org.fisco.bcos.web3j.abi.datatypes.Address; +import org.fisco.bcos.web3j.crypto.ECKeyPair; +import org.fisco.bcos.web3j.crypto.Keys; +import org.fisco.bcos.web3j.crypto.Sign; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -504,30 +503,19 @@ private ResponseData verifySignature( .verifySecp256k1SignatureFromWeId(rawData, credential.getSignature(), weIdDocument, null); if (errorCode.getCode() != ErrorCode.SUCCESS.getCode()) { - errorCode = DataToolUtils - .verifySignatureFromWeId(rawData, signatureData, weIdDocument, null); - if (errorCode.getCode() != ErrorCode.SUCCESS.getCode()) { - return new ResponseData<>(false, errorCode); - } + return new ResponseData<>(false, errorCode); } return new ResponseData<>(true, ErrorCode.SUCCESS); } } else { boolean result = DataToolUtils.verifySecp256k1Signature(rawData, - credential.getSignature(), new BigInteger(publicKey)) - || DataToolUtils - .verifySignature(rawData, signatureData, new BigInteger(publicKey)); + credential.getSignature(), new BigInteger(publicKey)); if (!result) { return new ResponseData<>(false, ErrorCode.CREDENTIAL_VERIFY_FAIL); } return new ResponseData<>(true, ErrorCode.SUCCESS); } - } catch (SignatureException e) { - logger.error( - "Generic signatureException occurred during verify signature " - + "when verifyCredential: ", e); - return new ResponseData<>(false, ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE); } catch (WeIdBaseException e) { logger.error( "Generic signatureException occurred during verify signature ", e); diff --git a/src/main/java/com/webank/weid/service/impl/EvidenceServiceImpl.java b/src/main/java/com/webank/weid/service/impl/EvidenceServiceImpl.java index 77e592460..18504e4f6 100644 --- a/src/main/java/com/webank/weid/service/impl/EvidenceServiceImpl.java +++ b/src/main/java/com/webank/weid/service/impl/EvidenceServiceImpl.java @@ -24,11 +24,13 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; +import java.util.Map; import com.google.common.base.Charsets; import com.google.common.io.Files; +import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; -import org.bcos.web3j.crypto.Sign.SignatureData; +import org.fisco.bcos.web3j.crypto.Sign.SignatureData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,6 +41,7 @@ import com.webank.weid.protocol.base.EvidenceInfo; import com.webank.weid.protocol.base.EvidenceSignInfo; import com.webank.weid.protocol.base.HashString; +import com.webank.weid.protocol.base.WeIdAuthentication; import com.webank.weid.protocol.base.WeIdDocument; import com.webank.weid.protocol.base.WeIdPrivateKey; import com.webank.weid.protocol.inf.Hashable; @@ -168,25 +171,93 @@ public ResponseData createEvidence(Hashable object, WeIdPrivateKey weIdP hashResp.getErrorMessage()); } if (!WeIdUtils.isPrivateKeyValid(weIdPrivateKey)) { - return new ResponseData<>(StringUtils.EMPTY, - ErrorCode.CREDENTIAL_PRIVATE_KEY_NOT_EXISTS); + return new ResponseData<>(StringUtils.EMPTY, ErrorCode.WEID_PRIVATEKEY_INVALID); } return hashToNewEvidence(hashResp.getResult(), weIdPrivateKey.getPrivateKey(), StringUtils.EMPTY); } + /** + * Create a new evidence to blockchain and return the hash value, with appending log. This will + * fail if evidence already exists. + * + * @param object the given Java object + * @param log appendable log entry - can be null or empty + * @param weIdAuthentication weid authentication (only checks private key) + */ + @Override + public ResponseData createEvidenceWithLog( + Hashable object, + String log, + WeIdAuthentication weIdAuthentication + ) { + ResponseData hashResp = getHashValue(object); + if (StringUtils.isEmpty(hashResp.getResult())) { + return new ResponseData<>(StringUtils.EMPTY, hashResp.getErrorCode(), + hashResp.getErrorMessage()); + } + if (weIdAuthentication == null + || !WeIdUtils.isPrivateKeyValid(weIdAuthentication.getWeIdPrivateKey())) { + return new ResponseData<>(StringUtils.EMPTY, ErrorCode.WEID_PRIVATEKEY_INVALID); + } + if (!DataToolUtils.isUtf8String(log)) { + logger.error("Evidence argument illegal input: log."); + return new ResponseData<>(StringUtils.EMPTY, ErrorCode.ILLEGAL_INPUT); + } + if (!isChainStringLengthValid(log)) { + return new ResponseData<>(StringUtils.EMPTY, ErrorCode.ON_CHAIN_STRING_TOO_LONG); + } + return hashToNewEvidence( + hashResp.getResult(), + weIdAuthentication.getWeIdPrivateKey().getPrivateKey(), + log); + } + /** * Add log entry for an existing evidence. This log will be recorded on blockchain permanently, * and finally it will be fetched as a list when trying to get evidence. * * @param hashValue hash value - * @param log log entry - can be null or empty + * @param log not null log entry * @param weIdPrivateKey the signer WeID's private key */ @Override public ResponseData addLogByHash(String hashValue, String log, WeIdPrivateKey weIdPrivateKey) { - if (!DataToolUtils.isValidHash(hashValue) || StringUtils.isEmpty(log) + return addByHash( + hashValue, + log, + weIdPrivateKey, + false + ); + } + + /** + * Add signature and log as a new signer to an existing evidence. Log can be empty. + * + * @param hashValue hash value + * @param log log entry + * @param weIdPrivateKey the signer WeID's private key + * @return true if succeeded, false otherwise + */ + @Override + public ResponseData addSignatureAndLogByHash(String hashValue, String log, + WeIdPrivateKey weIdPrivateKey) { + return addByHash( + hashValue, + log, + weIdPrivateKey, + true + ); + } + + private ResponseData addByHash( + String hashValue, + String log, + WeIdPrivateKey weIdPrivateKey, + boolean requireSig + ) { + if (!DataToolUtils.isValidHash(hashValue) || (StringUtils.isEmpty(log) && !requireSig) || !DataToolUtils.isUtf8String(log)) { logger.error("Evidence argument illegal input: hash or log."); return new ResponseData<>(false, ErrorCode.ILLEGAL_INPUT); @@ -195,33 +266,133 @@ public ResponseData addLogByHash(String hashValue, String log, return new ResponseData<>(false, ErrorCode.ON_CHAIN_STRING_TOO_LONG); } if (!WeIdUtils.isPrivateKeyValid(weIdPrivateKey)) { - return new ResponseData<>(false, ErrorCode.CREDENTIAL_PRIVATE_KEY_NOT_EXISTS); + return new ResponseData<>(false, ErrorCode.WEID_PRIVATEKEY_INVALID); } Long timestamp = DateUtils.getNoMillisecondTimeStamp(); - return evidenceServiceEngine.addLog( - hashValue, + if (requireSig) { + String signature = DataToolUtils.secp256k1Sign(hashValue, + new BigInteger(weIdPrivateKey.getPrivateKey())); + return evidenceServiceEngine.addLog( + hashValue, + signature, + log, + timestamp, + weIdPrivateKey.getPrivateKey() + ); + } else { + return evidenceServiceEngine.addLog( + hashValue, + StringUtils.EMPTY, + log, + timestamp, + weIdPrivateKey.getPrivateKey() + ); + } + } + + /** + * Add log entry for an existing evidence, appending on existing log entries. This log will be + * recorded on blockchain permanently, and finally it will be fetched as a list when trying to + * get evidence. Log must not be empty. It will firstly try to fetch the hash value given the + * custom key, and if the hash value does not exist, it will use the supplementing hash value + * (1st parameter) to make up. + * + * @param hashValueSupplement the hash value supplement if the custom key does not exist + * @param customKey custom key + * @param log Not null log entry + * @param weIdPrivateKey the signer WeID's private key + * @return true if succeeded, false otherwise + */ + @Override + public ResponseData addLogByCustomKey( + String hashValueSupplement, + String customKey, + String log, + WeIdPrivateKey weIdPrivateKey) { + return addByCustomKey( + hashValueSupplement, + customKey, log, - timestamp, - weIdPrivateKey.getPrivateKey() + weIdPrivateKey, + false ); } + /** + * Add signature and log as a new signer to an existing evidence. Log can be empty. + * + * @param hashValueSupplement the hash value supplement if the custom key does not exist + * @param customKey custom key + * @param log log entry + * @param weIdPrivateKey the signer WeID's private key + * @return true if succeeded, false otherwise + */ @Override - public ResponseData addLogByCustomKey(String customKey, String log, - WeIdPrivateKey weIdPrivateKey) { + public ResponseData addSignatureAndLogByCustomKey( + String hashValueSupplement, + String customKey, + String log, + WeIdPrivateKey weIdPrivateKey + ) { + return addByCustomKey( + hashValueSupplement, + customKey, + log, + weIdPrivateKey, + true + ); + } + + private ResponseData addByCustomKey( + String hashValueSupplement, + String customKey, + String log, + WeIdPrivateKey weIdPrivateKey, + boolean requireSig + ) { + if ((StringUtils.isEmpty(log) && !requireSig) || !DataToolUtils.isUtf8String(log)) { + logger.error("Evidence argument illegal input: log."); + return new ResponseData<>(false, ErrorCode.ILLEGAL_INPUT); + } if (StringUtils.isEmpty(customKey) || !DataToolUtils.isUtf8String(customKey)) { - logger.error("Evidence argument illegal input. "); + logger.error("Evidence argument illegal input: customKey."); return new ResponseData<>(false, ErrorCode.ILLEGAL_INPUT); } if (!isChainStringLengthValid(log)) { return new ResponseData<>(false, ErrorCode.ON_CHAIN_STRING_TOO_LONG); } ResponseData hashResp = evidenceServiceEngine.getHashByCustomKey(customKey); - if (StringUtils.isEmpty(hashResp.getResult())) { - return new ResponseData<>(false, hashResp.getErrorCode(), - hashResp.getErrorMessage()); + String hashValue = hashResp.getResult(); + if (StringUtils.isEmpty(hashValue)) { + logger.error("Failed to find the hash value from custom key: ", customKey); + if (StringUtils.isEmpty(hashValueSupplement)) { + return new ResponseData<>(false, hashResp.getErrorCode(), + hashResp.getErrorMessage()); + } + hashValue = hashValueSupplement; + } + Long timestamp = DateUtils.getNoMillisecondTimeStamp(); + if (requireSig) { + String signature = DataToolUtils.secp256k1Sign(hashValue, + new BigInteger(weIdPrivateKey.getPrivateKey())); + return evidenceServiceEngine.addLogByCustomKey( + hashValue, + signature, + log, + timestamp, + customKey, + weIdPrivateKey.getPrivateKey() + ); + } else { + return evidenceServiceEngine.addLogByCustomKey( + hashValue, + StringUtils.EMPTY, + log, + timestamp, + customKey, + weIdPrivateKey.getPrivateKey() + ); } - return this.addLogByHash(hashResp.getResult(), log, weIdPrivateKey); } /* (non-Javadoc) @@ -366,33 +537,6 @@ public ResponseData getEvidence(String evidenceKey) { } } - private ResponseData verifySignatureToSigner( - String rawData, - String signerWeId, - SignatureData signatureData - ) { - try { - ResponseData innerResponseData = - weIdService.getWeIdDocument(signerWeId); - if (innerResponseData.getErrorCode() != ErrorCode.SUCCESS.getCode()) { - logger.error( - "Error occurred when fetching WeIdentity DID document for: {}, msg: {}", - signerWeId, innerResponseData.getErrorMessage()); - return new ResponseData<>(false, ErrorCode.CREDENTIAL_WEID_DOCUMENT_ILLEGAL); - } - WeIdDocument weIdDocument = innerResponseData.getResult(); - ErrorCode errorCode = DataToolUtils - .verifySignatureFromWeId(rawData, signatureData, weIdDocument, null); - if (errorCode.getCode() != ErrorCode.SUCCESS.getCode()) { - return new ResponseData<>(false, errorCode); - } - return new ResponseData<>(true, ErrorCode.SUCCESS); - } catch (Exception e) { - logger.error("error occurred during verifying signatures from chain: ", e); - return new ResponseData<>(false, ErrorCode.CREDENTIAL_EVIDENCE_BASE_ERROR); - } - } - /** * Validate whether a credential created the evidence, and this evidence is signed by this WeID * - will perform on-Chain key check. @@ -487,21 +631,11 @@ public ResponseData verifySigner( evidenceInfo.getCredentialHash(), WeIdUtils.convertAddressToWeId(weId), signature); - if (verifyResp.getResult()) { - return verifyResp; - } else { - return verifySignatureToSigner( - evidenceInfo.getCredentialHash(), - WeIdUtils.convertAddressToWeId(weId), - signatureData - ); - } + return verifyResp; } else { try { boolean result = DataToolUtils .verifySecp256k1Signature(evidenceInfo.getCredentialHash(), signature, - new BigInteger(publicKey)) || DataToolUtils - .verifySignature(evidenceInfo.getCredentialHash(), signatureData, new BigInteger(publicKey)); if (!result) { @@ -579,7 +713,7 @@ public ResponseData createEvidenceWithLogAndCustomKey( } if (!WeIdUtils.isPrivateKeyValid(weIdPrivateKey)) { return new ResponseData<>(StringUtils.EMPTY, - ErrorCode.CREDENTIAL_PRIVATE_KEY_NOT_EXISTS); + ErrorCode.WEID_PRIVATEKEY_INVALID); } String privateKey = weIdPrivateKey.getPrivateKey(); try { @@ -648,4 +782,80 @@ public ResponseData getEvidenceByCustomKey(String customKey) { private boolean isChainStringLengthValid(String string) { return string.length() < WeIdConstant.ON_CHAIN_STRING_LENGTH; } + + /** + * Revoke an evidence - which can be un-revoked. + * + * @param object the object + * @param weIdAuthentication the weid authentication + * @return true if yes, false otherwise, with error codes + */ + @Override + public ResponseData revoke(Hashable object, WeIdAuthentication weIdAuthentication) { + ResponseData hashResp = getHashValue(object); + if (StringUtils.isEmpty(hashResp.getResult())) { + return new ResponseData<>(false, hashResp.getErrorCode(), + hashResp.getErrorMessage()); + } + if (weIdAuthentication == null + || !WeIdUtils.isPrivateKeyValid(weIdAuthentication.getWeIdPrivateKey())) { + return new ResponseData<>(false, ErrorCode.WEID_PRIVATEKEY_INVALID); + } + Long timestamp = DateUtils.getNoMillisecondTimeStamp(); + return evidenceServiceEngine.setAttribute( + hashResp.getResult(), + WeIdConstant.EVIDENCE_REVOKE_KEY, + StringUtils.EMPTY, + timestamp, + weIdAuthentication.getWeIdPrivateKey().getPrivateKey() + ); + } + + /** + * Revoke an evidence - which can be un-revoked. + * + * @param object the object + * @param weIdAuthentication the weid authentication + * @return true if yes, false otherwise, with error codes + */ + @Override + public ResponseData unRevoke(Hashable object, WeIdAuthentication weIdAuthentication) { + ResponseData hashResp = getHashValue(object); + if (StringUtils.isEmpty(hashResp.getResult())) { + return new ResponseData<>(false, hashResp.getErrorCode(), + hashResp.getErrorMessage()); + } + if (weIdAuthentication == null + || !WeIdUtils.isPrivateKeyValid(weIdAuthentication.getWeIdPrivateKey())) { + return new ResponseData<>(false, ErrorCode.WEID_PRIVATEKEY_INVALID); + } + Long timestamp = DateUtils.getNoMillisecondTimeStamp(); + return evidenceServiceEngine.setAttribute( + hashResp.getResult(), + WeIdConstant.EVIDENCE_UNREVOKE_KEY, + StringUtils.EMPTY, + timestamp, + weIdAuthentication.getWeIdPrivateKey().getPrivateKey() + ); + } + + /** + * Check whether this evidence is revoked by this WeID. + * + * @param evidenceInfo the EvidenceInfo + * @param weId the signer WeID + * @return true if revoked, false otherwise + */ + @Override + public ResponseData isRevoked(EvidenceInfo evidenceInfo, String weId) { + if (evidenceInfo == null) { + return new ResponseData<>(false, ErrorCode.ILLEGAL_INPUT); + } + Map evidenceSignInfos = evidenceInfo.getSignInfo(); + if (evidenceSignInfos == null || evidenceSignInfos.size() == 0 + || evidenceSignInfos.get(weId) == null) { + return new ResponseData<>(false, ErrorCode.WEID_DOES_NOT_EXIST); + } + return new ResponseData<>(evidenceSignInfos.get(weId).getRevoked(), ErrorCode.SUCCESS); + } } diff --git a/src/main/java/com/webank/weid/service/impl/PolicyServiceImpl.java b/src/main/java/com/webank/weid/service/impl/PolicyServiceImpl.java new file mode 100644 index 000000000..545d4a6ac --- /dev/null +++ b/src/main/java/com/webank/weid/service/impl/PolicyServiceImpl.java @@ -0,0 +1,223 @@ +package com.webank.weid.service.impl; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.collections4.CollectionUtils; +import org.fisco.bcos.web3j.crypto.Sign.SignatureData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.webank.weid.constant.ErrorCode; +import com.webank.weid.constant.WeIdConstant; +import com.webank.weid.protocol.base.ClaimPolicy; +import com.webank.weid.protocol.base.Cpt; +import com.webank.weid.protocol.base.CptBaseInfo; +import com.webank.weid.protocol.base.PresentationPolicyE; +import com.webank.weid.protocol.base.WeIdAuthentication; +import com.webank.weid.protocol.base.WeIdPrivateKey; +import com.webank.weid.protocol.request.CptMapArgs; +import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.protocol.response.RsvSignature; +import com.webank.weid.rpc.PolicyService; +import com.webank.weid.util.CredentialPojoUtils; +import com.webank.weid.util.DataToolUtils; +import com.webank.weid.util.WeIdUtils; + +/** + * Service implementations for operations on Evidence. + * + * @author chaoxinhu 2020.8 + */ + +public class PolicyServiceImpl extends AbstractService implements PolicyService { + + private static final Logger logger = LoggerFactory.getLogger(PolicyServiceImpl.class); + + /** + * Register Claim Policy on blockchain and assign it under a CPT ID. + * + * @param cptId CPT ID + * @param policyJson Policy Json file + * @param weIdAuthentication WeID auth + * @return claimPolicyId the Claim policy ID on-chain + */ + @Override + public ResponseData registerClaimPolicy(Integer cptId, String policyJson, + WeIdAuthentication weIdAuthentication) { + ResponseData policyIdResp = registerPolicyData(policyJson, weIdAuthentication); + if (policyIdResp.getResult() < 0) { + logger.error("Failed to register Claim Policy to blockchain."); + return policyIdResp; + } + // Append this claim policy id to the existing CPT's list + ResponseData> policiesResp = getClaimPoliciesFromCpt(cptId); + if (policiesResp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("Failed to get this CPT's claim policy list."); + return new ResponseData<>(-1, policiesResp.getErrorCode(), + policiesResp.getErrorMessage()); + } + List policies = policiesResp.getResult(); + if (CollectionUtils.isEmpty(policies)) { + policies = new ArrayList<>(); + } + policies.add(policyIdResp.getResult()); + ResponseData addResp = cptServiceEngine + .putPolicyIntoCpt(cptId, policies, weIdAuthentication.getWeIdPrivateKey()); + if (addResp.getResult() < 0) { + logger.error("Failed to add this policy ID {} into existing CPT ID's list: {}", + policyIdResp.getResult(), cptId); + return addResp; + } + return new ResponseData<>(policyIdResp.getResult(), ErrorCode.SUCCESS); + } + + private ResponseData registerPolicyData(String policyJson, WeIdAuthentication auth) { + if (!DataToolUtils.isValidJsonStr(policyJson)) { + logger.error("[registerPolicy] input json format illegal."); + return new ResponseData<>(null, ErrorCode.CPT_JSON_SCHEMA_INVALID); + } + ErrorCode errorCode = CredentialPojoUtils.isWeIdAuthenticationValid(auth); + if (errorCode != ErrorCode.SUCCESS) { + return new ResponseData<>(-1, errorCode); + } + CptMapArgs cptMapArgs = new CptMapArgs(); + cptMapArgs.setWeIdAuthentication(auth); + Map cptJsonSchemaMap = DataToolUtils.deserialize(policyJson, HashMap.class); + cptMapArgs.setCptJsonSchema(cptJsonSchemaMap); + WeIdPrivateKey weIdPrivateKey = auth.getWeIdPrivateKey(); + String cptJsonSchemaNew = DataToolUtils.serialize(cptMapArgs.getCptJsonSchema()); + RsvSignature rsvSignature = sign( + auth.getWeId(), + cptJsonSchemaNew, + weIdPrivateKey); + String address = WeIdUtils.convertWeIdToAddress(auth.getWeId()); + CptBaseInfo cptBaseInfo; + try { + cptBaseInfo = cptServiceEngine.registerCpt(address, cptJsonSchemaNew, rsvSignature, + weIdPrivateKey.getPrivateKey(), WeIdConstant.POLICY_DATA_INDEX).getResult(); + } catch (Exception e) { + logger.error("[register policy] register failed due to unknown error. ", e); + return new ResponseData<>(-1, ErrorCode.UNKNOW_ERROR.getCode(), + ErrorCode.UNKNOW_ERROR.getCodeDesc() + e.getMessage()); + } + if (cptBaseInfo != null && cptBaseInfo.getCptId() > 0) { + return new ResponseData<>(cptBaseInfo.getCptId(), ErrorCode.SUCCESS); + } else { + return new ResponseData<>(-1, ErrorCode.UNKNOW_ERROR); + } + } + + private RsvSignature sign( + String cptPublisher, + String jsonSchema, + WeIdPrivateKey cptPublisherPrivateKey) { + + StringBuilder sb = new StringBuilder(); + sb.append(cptPublisher); + sb.append(WeIdConstant.PIPELINE); + sb.append(jsonSchema); + SignatureData signatureData = DataToolUtils.secp256k1SignToSignature( + sb.toString(), new BigInteger(cptPublisherPrivateKey.getPrivateKey())); + return DataToolUtils.convertSignatureDataToRsv(signatureData); + } + + /** + * Get Claim Policy Json from blockchain given a policy ID. + * + * @param policyId the Claim Policy ID on-chain + * @return the claim Json + */ + @Override + public ResponseData getClaimPolicy(Integer policyId) { + if (policyId == null || policyId < 0) { + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + ResponseData policyResp = cptServiceEngine + .queryCpt(policyId, WeIdConstant.POLICY_DATA_INDEX); + if (policyResp.getResult() == null) { + return new ResponseData<>(null, ErrorCode.CPT_NOT_EXISTS.getCode(), + ErrorCode.CPT_NOT_EXISTS.getCodeDesc() + policyResp.getErrorMessage()); + } + ClaimPolicy claimPolicy = new ClaimPolicy(); + claimPolicy.setFieldsToBeDisclosed( + DataToolUtils.serialize(policyResp.getResult().getCptJsonSchema())); + return new ResponseData<>(claimPolicy, ErrorCode.SUCCESS); + } + + /** + * Get all claim policies from this CPT ID. + * + * @param cptId cpt id + * @return claim policies list + */ + @Override + public ResponseData> getClaimPoliciesFromCpt(Integer cptId) { + if (cptId == null || cptId < 0) { + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + return cptServiceEngine.getPolicyFromCpt(cptId); + } + + /** + * Register Presentation Policy which contains a number of claim policies. + * + * @param claimPolicyIdList claim policies list + * @param weIdAuthentication weid auth + * @return the presentation policy id + */ + @Override + public ResponseData registerPresentationPolicy(List claimPolicyIdList, + WeIdAuthentication weIdAuthentication) { + ErrorCode errorCode = CredentialPojoUtils.isWeIdAuthenticationValid(weIdAuthentication); + if (errorCode != ErrorCode.SUCCESS) { + return new ResponseData<>(-1, errorCode); + } + return cptServiceEngine + .putPolicyIntoPresentation(claimPolicyIdList, weIdAuthentication.getWeIdPrivateKey()); + } + + /** + * Get Presentation policies under this id from chain. + * + * @param presentationPolicyId presentation policy id + * @return the full presentation policy + */ + @Override + public ResponseData getPresentationPolicy(Integer presentationPolicyId) { + if (presentationPolicyId == null || presentationPolicyId < 0) { + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + PresentationPolicyE presentationPolicy = cptServiceEngine + .getPolicyFromPresentation(presentationPolicyId) + .getResult(); + if (presentationPolicy == null) { + return new ResponseData<>(null, ErrorCode.CREDENTIAL_CLAIM_POLICY_NOT_EXIST); + } + Map policyMap = new HashMap<>(); + for (Map.Entry entry : presentationPolicy.getPolicy().entrySet()) { + policyMap.put(entry.getKey(), getClaimPolicy(entry.getKey()).getResult()); + } + presentationPolicy.setPolicy(policyMap); + return new ResponseData<>(presentationPolicy, ErrorCode.SUCCESS); + } + + + /** + * Get all claim policies from chain. + * + * @param startPos start position + * @param num batch number + * @return claim policy list + */ + @Override + public ResponseData> getAllClaimPolicies(Integer startPos, Integer num) { + if (startPos < 0 || num < 1) { + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + return cptServiceEngine.getCptLists(startPos, num, WeIdConstant.POLICY_DATA_INDEX); + } +} 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 b987eb3db..fbbc4ed5f 100644 --- a/src/main/java/com/webank/weid/service/impl/WeIdServiceImpl.java +++ b/src/main/java/com/webank/weid/service/impl/WeIdServiceImpl.java @@ -25,8 +25,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; -import org.bcos.web3j.crypto.ECKeyPair; -import org.bcos.web3j.crypto.Keys; +import org.fisco.bcos.web3j.crypto.ECKeyPair; +import org.fisco.bcos.web3j.crypto.Keys; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -956,4 +956,9 @@ public ResponseData> getWeIdList( return new ResponseData<>(null, ErrorCode.UNKNOW_ERROR); } } + + @Override + public ResponseData getWeIdCount() { + return weIdServiceEngine.getWeIdCount(); + } } diff --git a/src/main/java/com/webank/weid/service/impl/callback/KeyManagerCallback.java b/src/main/java/com/webank/weid/service/impl/callback/KeyManagerCallback.java index a6b771440..c427e0f26 100644 --- a/src/main/java/com/webank/weid/service/impl/callback/KeyManagerCallback.java +++ b/src/main/java/com/webank/weid/service/impl/callback/KeyManagerCallback.java @@ -149,26 +149,18 @@ private boolean checkAuthority(GetEncryptKeyArgs arg, Map keyMap ); return false; } - ErrorCode errorCode = DataToolUtils.verifySignatureFromWeId( + ErrorCode errorCode = DataToolUtils.verifySecp256k1SignatureFromWeId( arg.getKeyId(), arg.getSignValue(), domRes.getResult(), null ); if (errorCode.getCode() != ErrorCode.SUCCESS.getCode()) { - errorCode = DataToolUtils.verifySecp256k1SignatureFromWeId( - arg.getKeyId(), - arg.getSignValue(), - domRes.getResult(), - null + logger.info( + "[checkAuthority] the data is be changed, this weid is {}.", + arg.getWeId() ); - if (errorCode.getCode() != ErrorCode.SUCCESS.getCode()) { - logger.info( - "[checkAuthority] the data is be changed, this weid is {}.", - arg.getWeId() - ); - return false; - } + return false; } return true; } diff --git a/src/main/java/com/webank/weid/service/impl/callback/RequestVerifyChallengeCallback.java b/src/main/java/com/webank/weid/service/impl/callback/RequestVerifyChallengeCallback.java index 868a3d1da..5cf8e0559 100644 --- a/src/main/java/com/webank/weid/service/impl/callback/RequestVerifyChallengeCallback.java +++ b/src/main/java/com/webank/weid/service/impl/callback/RequestVerifyChallengeCallback.java @@ -78,14 +78,10 @@ public RequestVerifyChallengeResponse onPush(RequestVerifyChallengeArgs args) { ErrorCode errorCode = DataToolUtils .verifySecp256k1SignatureFromWeId(rawData, signData, weIdDocResp.getResult(), null); if (errorCode.getCode() != ErrorCode.SUCCESS.getCode()) { - errorCode = DataToolUtils - .verifySignatureFromWeId(rawData, signData, weIdDocResp.getResult(), null); - if (errorCode.getCode() != ErrorCode.SUCCESS.getCode()) { - logger.error("[RequestVerifyChallengeCallback] verify challenge signature failed."); - result.setErrorCode(errorCode.getCode()); - result.setErrorMessage(errorCode.getCodeDesc()); - return result; - } + logger.error("[RequestVerifyChallengeCallback] verify challenge signature failed."); + result.setErrorCode(errorCode.getCode()); + result.setErrorMessage(errorCode.getCodeDesc()); + return result; } result.setErrorCode(ErrorCode.SUCCESS.getCode()); 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 2894e4cff..eddce5466 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 @@ -19,10 +19,14 @@ package com.webank.weid.service.impl.engine; +import java.util.List; + import com.webank.wedpr.selectivedisclosure.CredentialTemplateEntity; import com.webank.weid.protocol.base.Cpt; import com.webank.weid.protocol.base.CptBaseInfo; +import com.webank.weid.protocol.base.PresentationPolicyE; +import com.webank.weid.protocol.base.WeIdPrivateKey; import com.webank.weid.protocol.response.ResponseData; import com.webank.weid.protocol.response.RsvSignature; @@ -32,7 +36,7 @@ * @author tonychen 2019年6月25日 */ public interface CptServiceEngine extends ReloadStaticContract { - + /** * call cpt contract to update cpt based on cptid. * @@ -48,7 +52,8 @@ ResponseData updateCpt( String address, String cptJsonSchemaNew, RsvSignature rsvSignature, - String privateKey + String privateKey, + int dataStorageIndex ); /** @@ -66,7 +71,8 @@ ResponseData registerCpt( String address, String cptJsonSchemaNew, RsvSignature rsvSignature, - String privateKey + String privateKey, + int dataStorageIndex ); /** @@ -82,7 +88,8 @@ ResponseData registerCpt( String address, String cptJsonSchemaNew, RsvSignature rsvSignature, - String privateKey + String privateKey, + int dataStorageIndex ); /** @@ -91,7 +98,7 @@ ResponseData registerCpt( * @param cptId the id of the cpt * @return cpt info */ - ResponseData queryCpt(int cptId); + ResponseData queryCpt(int cptId, int dataStorageIndex); /** * query cpt credential template. @@ -100,4 +107,16 @@ ResponseData registerCpt( * @return Cpt Credential Template */ ResponseData queryCredentialTemplate(Integer cptId); + + ResponseData putPolicyIntoPresentation(List policyIdList, + WeIdPrivateKey weIdPrivateKey); + + ResponseData getPolicyFromPresentation(Integer presentationId); + + ResponseData putPolicyIntoCpt(Integer cptId, List policyIdList, + WeIdPrivateKey weIdPrivateKey); + + ResponseData> getPolicyFromCpt(Integer cptId); + + ResponseData> getCptLists(int startPos, int num, int dataStorageIndex); } diff --git a/src/main/java/com/webank/weid/service/impl/engine/DataBucketServiceEngine.java b/src/main/java/com/webank/weid/service/impl/engine/DataBucketServiceEngine.java index b0f0cd189..dd82317a2 100644 --- a/src/main/java/com/webank/weid/service/impl/engine/DataBucketServiceEngine.java +++ b/src/main/java/com/webank/weid/service/impl/engine/DataBucketServiceEngine.java @@ -9,83 +9,95 @@ public interface DataBucketServiceEngine { /** - * 以admin身份根据hash存放合约地址数据. + * 以admin身份根据bucketId存放合约地址数据. * - * @param hash 根据合约地址出来的hash值,全局唯一 + * @param bucketId 根据合约地址出来的bucketId值,全局唯一 * @param key 存放数据的key * @param value key对应的具体数据 * @param privateKey 存放数据的私钥信息 * @return 返回是否存放成功 */ - ResponseData put(String hash, String key, String value, WeIdPrivateKey privateKey); + ResponseData put(String bucketId, String key, String value, WeIdPrivateKey privateKey); /** - * 根据hash获取具体合约数据. + * 根据bucketId获取具体合约数据. * - * @param hash 合约地址出来的hash + * @param bucketId 合约地址出来的bucketId * @param key 需要获取数据的key * @return 返回具体数据 */ - ResponseData get(String hash, String key); + ResponseData get(String bucketId, String key); /** - * 根据Hash删除extra里面的key. + * 根据bucketId删除extra里面的key. * - * @param hash 根据合约地址出来的hash值,全局唯一 + * @param bucketId 根据合约地址出来的bucketId值,全局唯一 * @param key 存放数据的key * @param privateKey 存放数据的私钥信息, * @return 返回是否移除成功 */ - ResponseData removeExtraItem(String hash, String key, WeIdPrivateKey privateKey); + ResponseData removeExtraItem(String bucketId, String key, WeIdPrivateKey privateKey); /** - *删除Hash. + *删除bucketId. * - * @param hash 根据合约地址出来的hash值,全局唯一 + * @param bucketId 根据合约地址出来的bucketId值,全局唯一 * @param force 是否强制删除 * @param privateKey 存放数据的私钥信息, * @return 返回是否移除成功 */ ResponseData removeDataBucketItem( - String hash, + String bucketId, boolean force, WeIdPrivateKey privateKey ); /** - * 机构在使用某个hash的时候,可以根据自己的私钥信息来表示机构自己正在使用这个hash, - * 此时hash所有者也不可以删除此hash,如果不执行此方法,hash所有者可能会删除该hash. + * 机构在使用某个bucket的时候,可以根据自己的私钥信息来表示机构自己正在使用这个bucketId, + * 此时bucketId所有者也不可以删除此bucketId,如果不执行此方法,bucketId所有者可能会删除该bucketId. * - * @param hash 需要启用的hash + * @param bucketId 需要启用的bucketId * @param privateKey 机构自己的私钥信息 * @return 返回是否启用成功 */ - ResponseData enableHash(String hash, WeIdPrivateKey privateKey); + ResponseData enable(String bucketId, WeIdPrivateKey privateKey); /** - *机构停用某个hash,当机构在更换hash的时候,需要先把之前的hash给停用了, - *此时hash所有者才可以进行hash删除操作. + *机构停用某个bucket,当机构在更换bucketId的时候,需要先把之前的bucketId给停用了, + *此时bucketId所有者才可以进行bucketId删除操作. * - * @param hash 需要停用的hash - * @param privateKey 停用hash的用户私钥 + * @param bucketId 需要停用的bucketId + * @param privateKey 停用bucket的用户私钥 * @return 返回是否停用成功 */ - ResponseData disableHash(String hash, WeIdPrivateKey privateKey); + ResponseData disable(String bucketId, WeIdPrivateKey privateKey); /** - * 获取所有的hash信息. - * @return 返回所有的hash信息 + * 获取所有的bucket信息. + * @return 返回所有的bucket信息 */ - ResponseData> getAllHash(); + ResponseData> getAllBucket(); /** - *当用户私钥丢失的情况,管理员给hash进行所属重置. + *当用户私钥丢失的情况,管理员给bucket进行所属重置. * - * @param hash 需要重置的hash + * @param bucketId 需要重置的bucketId * @param newOwner 新的所属地址 - * @param privateKey 重置hash的用户私钥 + * @param privateKey 重置bucket的用户私钥 * @return 返回是否重置成功 */ - ResponseData updateHashOwner(String hash, String newOwner, WeIdPrivateKey privateKey); + ResponseData updateBucketOwner( + String bucketId, + String newOwner, + WeIdPrivateKey privateKey + ); + + /** + * 根据传入bucketId 获取当前bucket的启用列表. + * + * @param bucketId 查询的bucketId + * @return 返回启用用户列表 + */ + ResponseData> getActivatedUserList(String bucketId); } diff --git a/src/main/java/com/webank/weid/service/impl/engine/EngineFactory.java b/src/main/java/com/webank/weid/service/impl/engine/EngineFactory.java index 3ebc1b0d7..3a8c8e0d7 100644 --- a/src/main/java/com/webank/weid/service/impl/engine/EngineFactory.java +++ b/src/main/java/com/webank/weid/service/impl/engine/EngineFactory.java @@ -20,35 +20,20 @@ package com.webank.weid.service.impl.engine; import com.webank.weid.constant.CnsType; -import com.webank.weid.constant.WeIdConstant; -import com.webank.weid.service.impl.engine.fiscov1.AuthorityIssuerEngineV1; -import com.webank.weid.service.impl.engine.fiscov1.CptServiceEngineV1; -import com.webank.weid.service.impl.engine.fiscov1.EvidenceServiceEngineV1; -import com.webank.weid.service.impl.engine.fiscov1.RawTransactionServiceEngineV1; -import com.webank.weid.service.impl.engine.fiscov1.WeIdServiceEngineV1; import com.webank.weid.service.impl.engine.fiscov2.AuthorityIssuerEngineV2; import com.webank.weid.service.impl.engine.fiscov2.CptServiceEngineV2; import com.webank.weid.service.impl.engine.fiscov2.DataBucketServiceEngineV2; import com.webank.weid.service.impl.engine.fiscov2.EvidenceServiceEngineV2; import com.webank.weid.service.impl.engine.fiscov2.RawTransactionServiceEngineV2; import com.webank.weid.service.impl.engine.fiscov2.WeIdServiceEngineV2; -import com.webank.weid.util.PropertyUtils; public class EngineFactory { - /** - * fisco bcos version, default 1.3.x - */ - private static String fiscoVersion = PropertyUtils.getProperty("bcos.version", "1.3"); - /** * create WeIdServiceEngine. * @return WeIdServiceEngine object */ public static WeIdServiceEngine createWeIdServiceEngine() { - if (fiscoVersion.startsWith(WeIdConstant.FISCO_BCOS_1_X_VERSION_PREFIX)) { - return new WeIdServiceEngineV1(); - } return new WeIdServiceEngineV2(); } @@ -57,9 +42,6 @@ public static WeIdServiceEngine createWeIdServiceEngine() { * @return CptServiceEngine object */ public static CptServiceEngine createCptServiceEngine() { - if (fiscoVersion.startsWith(WeIdConstant.FISCO_BCOS_1_X_VERSION_PREFIX)) { - return new CptServiceEngineV1(); - } return new CptServiceEngineV2(); } @@ -68,9 +50,6 @@ public static CptServiceEngine createCptServiceEngine() { * @return CptServiceEngine object */ public static AuthorityIssuerServiceEngine createAuthorityIssuerServiceEngine() { - if (fiscoVersion.startsWith(WeIdConstant.FISCO_BCOS_1_X_VERSION_PREFIX)) { - return new AuthorityIssuerEngineV1(); - } return new AuthorityIssuerEngineV2(); } @@ -80,9 +59,6 @@ public static AuthorityIssuerServiceEngine createAuthorityIssuerServiceEngine() * @return EvidenceServiceEngine object */ public static EvidenceServiceEngine createEvidenceServiceEngine(Integer groupId) { - if (fiscoVersion.startsWith(WeIdConstant.FISCO_BCOS_1_X_VERSION_PREFIX)) { - return new EvidenceServiceEngineV1(); - } return new EvidenceServiceEngineV2(groupId); } @@ -91,9 +67,6 @@ public static EvidenceServiceEngine createEvidenceServiceEngine(Integer groupId) * @return RawTransactionServiceEngine object */ public static RawTransactionServiceEngine createRawTransactionServiceEngine() { - if (fiscoVersion.startsWith(WeIdConstant.FISCO_BCOS_1_X_VERSION_PREFIX)) { - return new RawTransactionServiceEngineV1(); - } return new RawTransactionServiceEngineV2(); } @@ -103,9 +76,6 @@ public static RawTransactionServiceEngine createRawTransactionServiceEngine() { * @return DataBucketServiceEngine object */ public static DataBucketServiceEngine createDataBucketServiceEngine(CnsType cnsType) { - if (fiscoVersion.startsWith(WeIdConstant.FISCO_BCOS_1_X_VERSION_PREFIX)) { - return null; - } return new DataBucketServiceEngineV2(cnsType); } } diff --git a/src/main/java/com/webank/weid/service/impl/engine/EvidenceServiceEngine.java b/src/main/java/com/webank/weid/service/impl/engine/EvidenceServiceEngine.java index f3dea091a..fa5d9aab5 100644 --- a/src/main/java/com/webank/weid/service/impl/engine/EvidenceServiceEngine.java +++ b/src/main/java/com/webank/weid/service/impl/engine/EvidenceServiceEngine.java @@ -45,11 +45,21 @@ ResponseData> batchCreateEvidence( ResponseData addLog( String hashValue, + String sig, String log, Long timestamp, String privateKey ); + ResponseData addLogByCustomKey( + String hashValue, + String signature, + String log, + Long timestamp, + String customKey, + String privateKey + ); + ResponseData getHashByCustomKey(String customKey); ResponseData createEvidenceWithCustomKey( @@ -75,4 +85,11 @@ ResponseData> batchCreateEvidenceWithCustomKey( ResponseData getInfoByCustomKey(String extraKey); + ResponseData setAttribute( + String hashValue, + String key, + String value, + Long timestamp, + String privateKey + ); } diff --git a/src/main/java/com/webank/weid/service/impl/engine/WeIdServiceEngine.java b/src/main/java/com/webank/weid/service/impl/engine/WeIdServiceEngine.java index 60b054657..0c7630475 100644 --- a/src/main/java/com/webank/weid/service/impl/engine/WeIdServiceEngine.java +++ b/src/main/java/com/webank/weid/service/impl/engine/WeIdServiceEngine.java @@ -99,4 +99,11 @@ ResponseData> getWeIdList( Integer indexInBlock, boolean direction ) throws Exception; + + /** + * get total weId. + * + * @return total weid + */ + ResponseData getWeIdCount(); } diff --git a/src/main/java/com/webank/weid/service/impl/engine/fiscov1/AuthorityIssuerEngineV1.java b/src/main/java/com/webank/weid/service/impl/engine/fiscov1/AuthorityIssuerEngineV1.java deleted file mode 100644 index 20ceab2bf..000000000 --- a/src/main/java/com/webank/weid/service/impl/engine/fiscov1/AuthorityIssuerEngineV1.java +++ /dev/null @@ -1,533 +0,0 @@ -/* - * Copyright© (2018-2019) WeBank Co., Ltd. - * - * This file is part of weid-java-sdk. - * - * weid-java-sdk is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * weid-java-sdk is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with weid-java-sdk. If not, see . - */ - -package com.webank.weid.service.impl.engine.fiscov1; - -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.bcos.web3j.abi.datatypes.Address; -import org.bcos.web3j.abi.datatypes.Bool; -import org.bcos.web3j.abi.datatypes.DynamicArray; -import org.bcos.web3j.abi.datatypes.DynamicBytes; -import org.bcos.web3j.abi.datatypes.Type; -import org.bcos.web3j.abi.datatypes.generated.Bytes32; -import org.bcos.web3j.abi.datatypes.generated.Int256; -import org.bcos.web3j.abi.datatypes.generated.Uint256; -import org.bcos.web3j.protocol.core.methods.response.TransactionReceipt; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.webank.weid.constant.ErrorCode; -import com.webank.weid.constant.WeIdConstant; -import com.webank.weid.contract.v1.AuthorityIssuerController; -import com.webank.weid.contract.v1.AuthorityIssuerController.AuthorityIssuerRetLogEventResponse; -import com.webank.weid.contract.v1.SpecificIssuerController; -import com.webank.weid.contract.v1.SpecificIssuerController.SpecificIssuerRetLogEventResponse; -import com.webank.weid.protocol.base.AuthorityIssuer; -import com.webank.weid.protocol.request.RegisterAuthorityIssuerArgs; -import com.webank.weid.protocol.request.RemoveAuthorityIssuerArgs; -import com.webank.weid.protocol.response.ResponseData; -import com.webank.weid.protocol.response.TransactionInfo; -import com.webank.weid.service.impl.engine.AuthorityIssuerServiceEngine; -import com.webank.weid.service.impl.engine.BaseEngine; -import com.webank.weid.util.DataToolUtils; -import com.webank.weid.util.DateUtils; -import com.webank.weid.util.WeIdUtils; - -/** - * AuthorityIssuerEngineV1 calls the authority issuer contract which runs on FISCO BCOS 1.3.x - * version. - * - * @author tonychen 2019年6月25日 - */ -public class AuthorityIssuerEngineV1 extends BaseEngine implements AuthorityIssuerServiceEngine { - - private static final Logger logger = LoggerFactory.getLogger(AuthorityIssuerEngineV1.class); - private static AuthorityIssuerController authorityIssuerController; - private static SpecificIssuerController specificIssuerController; - - /** - * 构造函数. - */ - public AuthorityIssuerEngineV1() { - if (authorityIssuerController == null || specificIssuerController == null) { - reload(); - } - } - - /** - * 重新加载静态合约对象. - */ - public void reload() { - authorityIssuerController = getContractService( - fiscoConfig.getIssuerAddress(), - AuthorityIssuerController.class); - specificIssuerController = getContractService( - fiscoConfig.getSpecificIssuerAddress(), - SpecificIssuerController.class); - } - - @Override - public ResponseData getWeIdFromOrgId(String orgId) { - return new ResponseData<>(StringUtils.EMPTY, ErrorCode.FISCO_BCOS_VERSION_NOT_SUPPORTED); - } - - @Override - public ResponseData recognizeWeId(Boolean type, String weId, String privateKey) { - return new ResponseData<>(false, ErrorCode.FISCO_BCOS_VERSION_NOT_SUPPORTED); - } - - /** - * Use the given private key to send the transaction to call the contract. - * - * @param privateKey the private key - */ - private AuthorityIssuerController reloadAuthorityIssuerContract(String privateKey) { - AuthorityIssuerController authorityIssuerController = reloadContract( - fiscoConfig.getIssuerAddress(), - privateKey, - AuthorityIssuerController.class - ); - return authorityIssuerController; - } - - private SpecificIssuerController reloadSpecificIssuerContract(String privateKey) { - SpecificIssuerController specificIssuerController = reloadContract( - fiscoConfig.getSpecificIssuerAddress(), - privateKey, - SpecificIssuerController.class - ); - return specificIssuerController; - } - - /** - * Verify Authority Issuer related events. - * - * @param event the Event - * @param opcode the Opcode - * @return the ErrorCode - */ - private static ErrorCode verifyAuthorityIssuerRelatedEvent( - AuthorityIssuerRetLogEventResponse event, - Integer opcode) { - if (event == null) { - return ErrorCode.ILLEGAL_INPUT; - } - if (event.addr == null || event.operation == null || event.retCode == null) { - return ErrorCode.ILLEGAL_INPUT; - } - Integer eventOpcode = event.operation.getValue().intValue(); - if (eventOpcode.equals(opcode)) { - Integer eventRetCode = event.retCode.getValue().intValue(); - return ErrorCode.getTypeByErrorCode(eventRetCode); - } else { - return ErrorCode.AUTHORITY_ISSUER_OPCODE_MISMATCH; - } - } - - /* (non-Javadoc) - * @see com.webank.weid.service.impl.engine.AuthorityIssuerController - * #addAuthorityIssuer(com.webank.weid.protocol.request.RegisterAuthorityIssuerArgs) - */ - @Override - public ResponseData addAuthorityIssuer(RegisterAuthorityIssuerArgs args) { - - AuthorityIssuer authorityIssuer = args.getAuthorityIssuer(); - String weAddress = WeIdUtils.convertWeIdToAddress(authorityIssuer.getWeId()); - String[] stringAttributes = loadNameToStringAttributes(authorityIssuer.getName()); - long[] longAttributes = new long[16]; - Long createDate = DateUtils.getNoMillisecondTimeStamp(); - longAttributes[0] = createDate; - Address addr = new Address(weAddress); - - try { - DynamicBytes accValue = new DynamicBytes(authorityIssuer - .getAccValue() - .getBytes(StandardCharsets.UTF_8) - ); - AuthorityIssuerController authorityIssuerController = reloadAuthorityIssuerContract( - args.getWeIdPrivateKey().getPrivateKey()); - Future future = authorityIssuerController.addAuthorityIssuer( - addr, - DataToolUtils.stringArrayToBytes32StaticArray(stringAttributes), - DataToolUtils.longArrayToInt256StaticArray(longAttributes), - accValue - ); - TransactionReceipt receipt = future.get( - WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, - TimeUnit.SECONDS - ); - TransactionInfo info = new TransactionInfo(receipt); - List eventList = - AuthorityIssuerController.getAuthorityIssuerRetLogEvents(receipt); - AuthorityIssuerRetLogEventResponse event = eventList.get(0); - ErrorCode errorCode = verifyAuthorityIssuerRelatedEvent(event, - WeIdConstant.ADD_AUTHORITY_ISSUER_OPCODE); - return new ResponseData<>(errorCode.getCode() == ErrorCode.SUCCESS.getCode(), - errorCode, info); - } catch (TimeoutException e) { - logger.error("register authority issuer failed due to system timeout. ", e); - return new ResponseData<>(false, ErrorCode.TRANSACTION_TIMEOUT); - } catch (InterruptedException | ExecutionException e) { - logger.error("register authority issuer failed due to transaction error. ", e); - return new ResponseData<>(false, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } - } - - private String[] loadNameToStringAttributes(String name) { - String[] nameArray = new String[WeIdConstant.AUTHORITY_ISSUER_ARRAY_LEGNTH]; - nameArray[0] = name; - return nameArray; - } - - /* (non-Javadoc) - * @see com.webank.weid.service.impl.engine.AuthorityIssuerController#removeAuthorityIssuer - * (com.webank.weid.protocol.request.RemoveAuthorityIssuerArgs) - */ - @Override - public ResponseData removeAuthorityIssuer(RemoveAuthorityIssuerArgs args) { - String weId = args.getWeId(); - Address addr = new Address(WeIdUtils.convertWeIdToAddress(weId)); - try { - AuthorityIssuerController authorityIssuerController = reloadAuthorityIssuerContract( - args.getWeIdPrivateKey().getPrivateKey()); - Future future = authorityIssuerController - .removeAuthorityIssuer(addr); - TransactionReceipt receipt = - future.get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS); - List eventList = - AuthorityIssuerController.getAuthorityIssuerRetLogEvents(receipt); - - TransactionInfo info = new TransactionInfo(receipt); - AuthorityIssuerRetLogEventResponse event = eventList.get(0); - if (event != null) { - ErrorCode errorCode = verifyAuthorityIssuerRelatedEvent( - event, - WeIdConstant.REMOVE_AUTHORITY_ISSUER_OPCODE - ); - if (ErrorCode.SUCCESS.getCode() != errorCode.getCode()) { - return new ResponseData<>(false, errorCode, info); - } else { - return new ResponseData<>(true, errorCode, info); - } - } else { - logger.error("remove authority issuer failed, transcation event decoding failure."); - return new ResponseData<>(false, ErrorCode.AUTHORITY_ISSUER_ERROR, info); - } - } catch (TimeoutException e) { - logger.error("remove authority issuer failed due to system timeout. ", e); - return new ResponseData<>(false, ErrorCode.TRANSACTION_TIMEOUT); - } catch (InterruptedException | ExecutionException e) { - logger.error("remove authority issuer failed due to transaction error. ", e); - return new ResponseData<>(false, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } - } - - /* (non-Javadoc) - * @see com.webank.weid.service.impl.engine.AuthorityIssuerController - * #isAuthorityIssuer(java.lang.String) - */ - @Override - public ResponseData isAuthorityIssuer(String address) { - ResponseData resultData = new ResponseData(); - Address addr = new Address(address); - try { - Future future = authorityIssuerController.isAuthorityIssuer(addr); - Boolean result = - future.get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS).getValue(); - resultData.setResult(result); - if (result) { - resultData.setErrorCode(ErrorCode.SUCCESS); - } else { - resultData.setErrorCode(ErrorCode.AUTHORITY_ISSUER_CONTRACT_ERROR_NOT_EXISTS); - } - return resultData; - } catch (TimeoutException e) { - logger.error("check authority issuer id failed due to system timeout. ", e); - return new ResponseData<>(false, ErrorCode.TRANSACTION_TIMEOUT); - } catch (InterruptedException | ExecutionException e) { - logger.error("check authority issuer id failed due to transaction error. ", e); - return new ResponseData<>(false, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } - } - - /* (non-Javadoc) - * @see com.webank.weid.service.impl.engine.AuthorityIssuerController - * #getAuthorityIssuerInfoNonAccValue(java.lang.String) - */ - @Override - public ResponseData getAuthorityIssuerInfoNonAccValue(String weId) { - - ResponseData resultData = new ResponseData(); - Address addr = new Address(WeIdUtils.convertWeIdToAddress(weId)); - try { - - List rawResult = - authorityIssuerController - .getAuthorityIssuerInfoNonAccValue(addr) - .get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS); - if (rawResult == null) { - return new ResponseData<>(null, ErrorCode.AUTHORITY_ISSUER_ERROR); - } - - DynamicArray bytes32Attributes = (DynamicArray) rawResult.get(0); - DynamicArray int256Attributes = (DynamicArray) rawResult.get(1); - - AuthorityIssuer result = new AuthorityIssuer(); - result.setWeId(weId); - String name = extractNameFromBytes32Attributes(bytes32Attributes.getValue()); - Long createDate = Long - .valueOf(int256Attributes.getValue().get(0).getValue().longValue()); - if (StringUtils.isEmpty(name) && createDate.equals(WeIdConstant.LONG_VALUE_ZERO)) { - return new ResponseData<>( - null, ErrorCode.AUTHORITY_ISSUER_CONTRACT_ERROR_NOT_EXISTS - ); - } - result.setName(name); - result.setCreated(createDate); - // Accumulator Value is unable to load due to Solidity 0.4.4 restrictions - left blank. - result.setAccValue(""); - resultData.setResult(result); - return resultData; - } catch (TimeoutException e) { - logger.error("query authority issuer failed due to system timeout. ", e); - return new ResponseData<>(null, ErrorCode.TRANSACTION_TIMEOUT); - } catch (InterruptedException | ExecutionException e) { - logger.error("query authority issuer failed due to transaction error. ", e); - return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } - } - - private String extractNameFromBytes32Attributes(List bytes32Array) { - StringBuffer name = new StringBuffer(); - int maxLength = WeIdConstant.MAX_AUTHORITY_ISSUER_NAME_LENGTH / 32; - for (int i = 0; i < maxLength; i++) { - name.append(DataToolUtils.bytes32ToString(bytes32Array.get(i))); - } - return name.toString(); - } - - /* (non-Javadoc) - * @see com.webank.weid.service.impl.engine.AuthorityIssuerController - * #getAuthorityIssuerAddressList(java.lang.Integer, java.lang.Integer) - */ - @Override - public List getAuthorityIssuerAddressList(Integer index, Integer num) { - - List addrList = new ArrayList<>(); - try { - List
addressList = authorityIssuerController - .getAuthorityIssuerAddressList(new Uint256(index), new Uint256(num)) - .get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS) - .getValue(); - if (CollectionUtils.isNotEmpty(addressList)) { - for (Address addr : addressList) { - addrList.add(addr.toString()); - } - } - } catch (TimeoutException e) { - logger.error("query authority issuer list failed due to system timeout. ", e); - } catch (InterruptedException | ExecutionException e) { - logger.error("query authority issuer list failed due to transaction error. ", e); - } - - return addrList; - } - - /* (non-Javadoc) - * @see com.webank.weid.service.impl.engine.AuthorityIssuerController - * #removeIssuer(java.lang.String, java.lang.String) - */ - @Override - public ResponseData removeIssuer(String issuerType, String issuerAddress, - String privateKey) { - try { - SpecificIssuerController specificIssuerController = reloadSpecificIssuerContract( - privateKey); - Future future = specificIssuerController - .removeIssuer(DataToolUtils.stringToBytes32(issuerType), - new Address(issuerAddress)); - TransactionReceipt receipt = - future.get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS); - TransactionInfo info = new TransactionInfo(receipt); - ErrorCode errorCode = resolveSpecificIssuerEvents(receipt, false, issuerAddress); - return new ResponseData<>(errorCode.getCode() == ErrorCode.SUCCESS.getCode(), - errorCode, info); - } catch (TimeoutException e) { - logger.error("remove issuer from type failed due to system timeout. ", e); - return new ResponseData<>(false, ErrorCode.TRANSACTION_TIMEOUT); - } catch (InterruptedException | ExecutionException e) { - logger.error("remove issuer from type failed due to transaction error. ", e); - return new ResponseData<>(false, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } - } - - private ErrorCode resolveSpecificIssuerEvents( - TransactionReceipt transactionReceipt, - boolean isRegister, - String address) { - List eventList = - SpecificIssuerController.getSpecificIssuerRetLogEvents(transactionReceipt); - - SpecificIssuerRetLogEventResponse event = eventList.get(0); - if (event != null) { - if (isRegister) { - // this might be the register type, or the register specific issuer case - if (event.operation.getValue().intValue() - != WeIdConstant.ADD_AUTHORITY_ISSUER_OPCODE - || !StringUtils.equalsIgnoreCase(event.addr.toString(), address)) { - return ErrorCode.TRANSACTION_EXECUTE_ERROR; - } - } else { - // this is the remove specific issuer case - if (event.operation.getValue().intValue() - != WeIdConstant.REMOVE_AUTHORITY_ISSUER_OPCODE - || !StringUtils.equalsIgnoreCase(event.addr.toString(), address)) { - return ErrorCode.TRANSACTION_EXECUTE_ERROR; - } - } - Integer eventRetCode = event.retCode.getValue().intValue(); - return ErrorCode.getTypeByErrorCode(eventRetCode); - } else { - logger.error( - "specific issuer type resolution failed due to event decoding failure."); - return ErrorCode.UNKNOW_ERROR; - } - } - - /* (non-Javadoc) - * @see com.webank.weid.service.impl.engine.AuthorityIssuerController - * #isSpecificTypeIssuer(java.lang.String, java.lang.String) - */ - @Override - public ResponseData isSpecificTypeIssuer(String issuerType, String address) { - try { - Future future = specificIssuerController - .isSpecificTypeIssuer(DataToolUtils.stringToBytes32(issuerType), - new Address(address)); - Boolean result = - future.get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS).getValue(); - if (!result) { - return new ResponseData<>(result, - ErrorCode.SPECIFIC_ISSUER_CONTRACT_ERROR_ALREADY_NOT_EXIST); - } - return new ResponseData<>(result, ErrorCode.SUCCESS); - } catch (TimeoutException e) { - logger.error("check issuer type failed due to system timeout. ", e); - return new ResponseData<>(false, ErrorCode.TRANSACTION_TIMEOUT); - } catch (InterruptedException | ExecutionException e) { - logger.error("check issuer type failed due to transaction error. ", e); - return new ResponseData<>(false, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } - } - - /* (non-Javadoc) - * @see com.webank.weid.service.impl.engine.AuthorityIssuerController - * #getSpecificTypeIssuerList(java.lang.String, java.lang.Integer, java.lang.Integer) - */ - @Override - public ResponseData> getSpecificTypeIssuerList(String issuerType, Integer index, - Integer num) { - try { - List
addresses = specificIssuerController - .getSpecificTypeIssuerList(DataToolUtils.stringToBytes32(issuerType), - new Uint256(index), new Uint256(num)) - .get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS) - .getValue(); - List addressList = new ArrayList<>(); - for (Address addr : addresses) { - if (!WeIdUtils.isEmptyAddress(addr)) { - addressList.add(addr.toString()); - } - } - return new ResponseData<>(addressList, ErrorCode.SUCCESS); - } catch (TimeoutException e) { - logger.error("get all specific issuers failed due to system timeout. ", e); - return new ResponseData<>(null, ErrorCode.TRANSACTION_TIMEOUT); - } catch (InterruptedException | ExecutionException e) { - logger.error("get all specific issuers failed due to transaction error. ", e); - return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } - } - - /* (non-Javadoc) - * @see com.webank.weid.service.impl.engine.IssuerContractController - * #registerIssuerType(java.lang.String) - */ - @Override - public ResponseData registerIssuerType(String issuerType, String privateKey) { - try { - SpecificIssuerController specificIssuerController = reloadSpecificIssuerContract( - privateKey); - Future future = specificIssuerController - .registerIssuerType(DataToolUtils.stringToBytes32(issuerType)); - TransactionReceipt receipt = - future.get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS); - TransactionInfo info = new TransactionInfo(receipt); - // pass-in empty address - String emptyAddress = new Address(BigInteger.ZERO).toString(); - ErrorCode errorCode = resolveSpecificIssuerEvents(receipt, true, emptyAddress); - return new ResponseData<>(errorCode.getCode() == ErrorCode.SUCCESS.getCode(), - errorCode, info); - } catch (TimeoutException e) { - logger.error("register issuer type failed due to system timeout. ", e); - return new ResponseData<>(false, ErrorCode.TRANSACTION_TIMEOUT); - } catch (InterruptedException | ExecutionException e) { - logger.error("register issuer type failed due to transaction error. ", e); - return new ResponseData<>(false, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } - } - - /* (non-Javadoc) - * @see com.webank.weid.service.impl.engine.IssuerContractController - * #addIssuer(java.lang.String, java.lang.String) - */ - @Override - public ResponseData addIssuer(String issuerType, String issuerAddress, - String privateKey) { - try { - SpecificIssuerController specificIssuerController = reloadSpecificIssuerContract( - privateKey); - Future future = specificIssuerController - .addIssuer(DataToolUtils.stringToBytes32(issuerType), new Address(issuerAddress)); - TransactionReceipt receipt = - future.get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS); - TransactionInfo info = new TransactionInfo(receipt); - ErrorCode errorCode = resolveSpecificIssuerEvents(receipt, true, issuerAddress); - return new ResponseData<>(errorCode.getCode() == ErrorCode.SUCCESS.getCode(), - errorCode, info); - } catch (TimeoutException e) { - logger.error("add issuer into type failed due to system timeout. ", e); - return new ResponseData<>(false, ErrorCode.TRANSACTION_TIMEOUT); - } catch (InterruptedException | ExecutionException e) { - logger.error("add issuer into type failed due to transaction error. ", e); - return new ResponseData<>(false, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } - } - -} 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 index 4b807f6ba..e69de29bb 100644 --- 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 @@ -1,580 +0,0 @@ -/* - * Copyright© (2018-2019) WeBank Co., Ltd. - * - * This file is part of weid-java-sdk. - * - * weid-java-sdk is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * weid-java-sdk is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with weid-java-sdk. If not, see . - */ - -package com.webank.weid.service.impl.engine.fiscov1; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.stream.Collectors; - -import com.webank.wedpr.selectivedisclosure.CredentialTemplateEntity; -import com.webank.wedpr.selectivedisclosure.IssuerClient; -import com.webank.wedpr.selectivedisclosure.IssuerResult; -import com.webank.wedpr.selectivedisclosure.proto.TemplatePublicKey; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.bcos.web3j.abi.EventEncoder; -import org.bcos.web3j.abi.TypeReference; -import org.bcos.web3j.abi.datatypes.Address; -import org.bcos.web3j.abi.datatypes.DynamicArray; -import org.bcos.web3j.abi.datatypes.DynamicBytes; -import org.bcos.web3j.abi.datatypes.Event; -import org.bcos.web3j.abi.datatypes.StaticArray; -import org.bcos.web3j.abi.datatypes.Type; -import org.bcos.web3j.abi.datatypes.generated.Bytes32; -import org.bcos.web3j.abi.datatypes.generated.Int256; -import org.bcos.web3j.abi.datatypes.generated.Uint256; -import org.bcos.web3j.abi.datatypes.generated.Uint8; -import org.bcos.web3j.crypto.Sign; -import org.bcos.web3j.protocol.Web3j; -import org.bcos.web3j.protocol.core.DefaultBlockParameterNumber; -import org.bcos.web3j.protocol.core.methods.response.EthBlock; -import org.bcos.web3j.protocol.core.methods.response.EthGetTransactionReceipt; -import org.bcos.web3j.protocol.core.methods.response.Log; -import org.bcos.web3j.protocol.core.methods.response.Transaction; -import org.bcos.web3j.protocol.core.methods.response.TransactionReceipt; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.webank.weid.constant.DataDriverConstant; -import com.webank.weid.constant.ErrorCode; -import com.webank.weid.constant.WeIdConstant; -import com.webank.weid.contract.v1.CptController; -import com.webank.weid.contract.v1.CptController.CredentialTemplateEventResponse; -import com.webank.weid.contract.v1.CptController.RegisterCptRetLogEventResponse; -import com.webank.weid.contract.v1.CptController.UpdateCptRetLogEventResponse; -import com.webank.weid.exception.DataTypeCastException; -import com.webank.weid.exception.DatabaseException; -import com.webank.weid.exception.ResolveAttributeException; -import com.webank.weid.protocol.base.Cpt; -import com.webank.weid.protocol.base.CptBaseInfo; -import com.webank.weid.protocol.response.ResponseData; -import com.webank.weid.protocol.response.RsvSignature; -import com.webank.weid.protocol.response.TransactionInfo; -import com.webank.weid.service.impl.engine.BaseEngine; -import com.webank.weid.service.impl.engine.CptServiceEngine; -import com.webank.weid.suite.api.persistence.PersistenceFactory; -import com.webank.weid.suite.api.persistence.inf.Persistence; -import com.webank.weid.suite.api.persistence.params.PersistenceType; -import com.webank.weid.util.CredentialPojoUtils; -import com.webank.weid.util.DataToolUtils; -import com.webank.weid.util.JsonUtil; -import com.webank.weid.util.PropertyUtils; -import com.webank.weid.util.TransactionUtils; -import com.webank.weid.util.WeIdUtils; - -/** - * CptServiceEngine calls the authority issuer contract which runs on FISCO BCOS 1.3.x. - * - * @author tonychen 2019年6月25日 - */ -public class CptServiceEngineV1 extends BaseEngine implements CptServiceEngine { - - private static final Logger logger = LoggerFactory.getLogger(CptServiceEngineV1.class); - - private static CptController cptController; - - private static String CREDENTIALTEMPLATETOPIC; - - private static Persistence dataDriver; - - private static PersistenceType persistenceType; - - static { - Event event = new Event( - "CredentialTemplate", - Arrays.>asList(), - Arrays.>asList( - new TypeReference() { - }, - new TypeReference() { - }, - new TypeReference() { - })); - CREDENTIALTEMPLATETOPIC = EventEncoder.encode(event); - } - - /** - * 构造函数. - */ - public CptServiceEngineV1() { - if (cptController == null) { - reload(); - } - } - - /** - * 重新加载静态合约对象. - */ - public void reload() { - cptController = getContractService(fiscoConfig.getCptAddress(), CptController.class); - } - - /** - * Verify Register CPT related events. - * - * @param transactionReceipt the TransactionReceipt - * @return the ErrorCode - */ - public static ResponseData resolveRegisterCptEvents( - TransactionReceipt transactionReceipt) { - List event = CptController.getRegisterCptRetLogEvents( - transactionReceipt - ); - - if (CollectionUtils.isEmpty(event)) { - logger.error("[registerCpt] event is empty"); - return new ResponseData<>(null, ErrorCode.CPT_EVENT_LOG_NULL); - } - - return getResultByResolveEvent( - event.get(0).retCode, - event.get(0).cptId, - event.get(0).cptVersion, - transactionReceipt - ); - } - - /** - * Verify Update CPT related events. - * - * @param transactionReceipt the TransactionReceipt - * @return the ErrorCode - */ - public static ResponseData resolveUpdateCptEvents( - TransactionReceipt transactionReceipt) { - List event = CptController.getUpdateCptRetLogEvents( - transactionReceipt - ); - - if (CollectionUtils.isEmpty(event)) { - logger.error("[updateCpt] event is empty"); - return new ResponseData<>(null, ErrorCode.CPT_EVENT_LOG_NULL); - } - - return getResultByResolveEvent( - event.get(0).retCode, - event.get(0).cptId, - event.get(0).cptVersion, - transactionReceipt - ); - } - - /** - * Resolve CPT Event. - * - * @param retCode the retCode - * @param cptId the CptId - * @param cptVersion the CptVersion - * @param receipt the transactionReceipt - * @return the result - */ - public static ResponseData getResultByResolveEvent( - Uint256 retCode, - Uint256 cptId, - Int256 cptVersion, - TransactionReceipt receipt) { - - TransactionInfo info = new TransactionInfo(receipt); - // register - if (DataToolUtils.uint256ToInt(retCode) - == ErrorCode.CPT_ID_AUTHORITY_ISSUER_EXCEED_MAX.getCode()) { - logger.error("[getResultByResolveEvent] cptId limited max value. cptId:{}", - DataToolUtils.uint256ToInt(cptId)); - return new ResponseData<>(null, ErrorCode.CPT_ID_AUTHORITY_ISSUER_EXCEED_MAX, info); - } - - if (DataToolUtils.uint256ToInt(retCode) == ErrorCode.CPT_ALREADY_EXIST.getCode()) { - logger.error("[getResultByResolveEvent] cpt already exists on chain. cptId:{}", - DataToolUtils.uint256ToInt(cptId)); - return new ResponseData<>(null, ErrorCode.CPT_ALREADY_EXIST, info); - } - - if (DataToolUtils.uint256ToInt(retCode) == ErrorCode.CPT_NO_PERMISSION.getCode()) { - logger.error("[getResultByResolveEvent] no permission. cptId:{}", - DataToolUtils.uint256ToInt(cptId)); - return new ResponseData<>(null, ErrorCode.CPT_NO_PERMISSION, info); - } - - // register and update - if (DataToolUtils.uint256ToInt(retCode) - == ErrorCode.CPT_PUBLISHER_NOT_EXIST.getCode()) { - logger.error("[getResultByResolveEvent] publisher does not exist. cptId:{}", - DataToolUtils.uint256ToInt(cptId)); - return new ResponseData<>(null, ErrorCode.CPT_PUBLISHER_NOT_EXIST, info); - } - - // update - if (DataToolUtils.uint256ToInt(retCode) - == ErrorCode.CPT_NOT_EXISTS.getCode()) { - logger.error("[getResultByResolveEvent] cpt id : {} does not exist.", - DataToolUtils.uint256ToInt(cptId)); - return new ResponseData<>(null, ErrorCode.CPT_NOT_EXISTS, info); - } - - CptBaseInfo result = new CptBaseInfo(); - result.setCptId(DataToolUtils.uint256ToInt(cptId)); - result.setCptVersion(DataToolUtils.int256ToInt(cptVersion)); - - return new ResponseData<>(result, ErrorCode.SUCCESS, info); - } - - private Persistence getDataDriver() { - String type = PropertyUtils.getProperty("persistence_type"); - if (type.equals("mysql")) { - persistenceType = PersistenceType.Mysql; - } else if (type.equals("redis")) { - persistenceType = PersistenceType.Redis; - } - if (dataDriver == null) { - dataDriver = PersistenceFactory.build(persistenceType); - } - return dataDriver; - } - - /* (non-Javadoc) - * @see com.webank.weid.service.impl.engine.CptEngineController - * #updateCpt(int, java.lang.String, java.lang.String, - * com.webank.weid.protocol.response.RsvSignature) - */ - @Override - public ResponseData updateCpt(int cptId, String address, String cptJsonSchemaNew, - RsvSignature rsvSignature, String privateKey) { - - StaticArray bytes32Array = DataToolUtils.stringArrayToBytes32StaticArray( - new String[WeIdConstant.CPT_STRING_ARRAY_LENGTH] - ); - - TransactionReceipt receipt; - try { - CptController cptController = - reloadContract(fiscoConfig.getCptAddress(), privateKey, CptController.class); - receipt = cptController.updateCpt( - DataToolUtils.intToUint256(cptId), - new Address(address), - TransactionUtils.getParamUpdated(WeIdConstant.CPT_LONG_ARRAY_LENGTH), - bytes32Array, - TransactionUtils.getParamJsonSchema(cptJsonSchemaNew), - rsvSignature.getV(), - rsvSignature.getR(), - rsvSignature.getS() - ).get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS); - ResponseData response = resolveUpdateCptEvents(receipt); - if (response.getErrorCode().intValue() != ErrorCode.SUCCESS.getCode()) { - return response; - } - ErrorCode errorCode = processTemplate(cptId, cptJsonSchemaNew); - int code = errorCode.getCode(); - if (code != ErrorCode.SUCCESS.getCode()) { - logger.error("[updateCpt] save credential template failed. errorcode:{} ", code); - return new ResponseData(null, ErrorCode.TRANSACTION_TIMEOUT); - } - return response; - } catch (TimeoutException e) { - logger.error("[updateCpt] transaction execute with timeout exception. ", e); - return new ResponseData(null, ErrorCode.TRANSACTION_TIMEOUT); - } catch (InterruptedException | ExecutionException e) { - logger.error("[updateCpt] transaction execute with exception. ", e); - return new ResponseData(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } - - } - - /* (non-Javadoc) - * @see com.webank.weid.service.impl.engine.CptEngineController - * #registerCpt(int, java.lang.String, java.lang.String, - * com.webank.weid.protocol.response.RsvSignature) - */ - @Override - public ResponseData registerCpt(int cptId, String address, String cptJsonSchemaNew, - RsvSignature rsvSignature, String privateKey) { - StaticArray bytes32Array = DataToolUtils.stringArrayToBytes32StaticArray( - new String[WeIdConstant.CPT_STRING_ARRAY_LENGTH] - ); - - TransactionReceipt receipt; - try { - CptController cptController = - reloadContract(fiscoConfig.getCptAddress(), privateKey, CptController.class); - receipt = cptController.registerCpt( - DataToolUtils.intToUint256(cptId), - new Address(address), - TransactionUtils.getParamCreated(WeIdConstant.CPT_LONG_ARRAY_LENGTH), - bytes32Array, - TransactionUtils.getParamJsonSchema(cptJsonSchemaNew), - rsvSignature.getV(), - rsvSignature.getR(), - rsvSignature.getS() - ).get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS); - - ResponseData response = resolveRegisterCptEvents(receipt); - if (response.getErrorCode().intValue() != ErrorCode.SUCCESS.getCode()) { - return response; - } - ErrorCode errorCode = processTemplate(cptId, cptJsonSchemaNew); - int code = errorCode.getCode(); - if (code != ErrorCode.SUCCESS.getCode()) { - logger.error("[updateCpt] save credential template failed. errorcode:{} ", code); - return new ResponseData(null, ErrorCode.TRANSACTION_TIMEOUT); - } - return response; - } catch (TimeoutException e) { - logger.error("[updateCpt] transaction execute with timeout exception. ", e); - return new ResponseData(null, ErrorCode.TRANSACTION_TIMEOUT); - } catch (InterruptedException | ExecutionException e) { - logger.error("[updateCpt] transaction execute with exception. ", e); - return new ResponseData(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } - } - - - /* (non-Javadoc) - * @see com.webank.weid.service.impl.engine.CptEngineController - * #registerCpt(java.lang.String, java.lang.String, - * com.webank.weid.protocol.response.RsvSignature) - */ - @Override - public ResponseData registerCpt(String address, String cptJsonSchemaNew, - RsvSignature rsvSignature, String privateKey) { - - StaticArray bytes32Array = DataToolUtils.stringArrayToBytes32StaticArray( - new String[WeIdConstant.CPT_STRING_ARRAY_LENGTH] - ); - - TransactionReceipt receipt; - try { - CptController cptController = - reloadContract(fiscoConfig.getCptAddress(), privateKey, CptController.class); - // the case to register a CPT with a pre-set CPT ID - receipt = cptController.registerCpt( - new Address(address), - TransactionUtils.getParamCreated(WeIdConstant.CPT_LONG_ARRAY_LENGTH), - bytes32Array, - TransactionUtils.getParamJsonSchema(cptJsonSchemaNew), - rsvSignature.getV(), - rsvSignature.getR(), - rsvSignature.getS() - ).get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS); - - ResponseData response = resolveRegisterCptEvents(receipt); - if (response.getErrorCode().intValue() != ErrorCode.SUCCESS.getCode()) { - return response; - } - int cptId = response.getResult().getCptId(); - ErrorCode errorCode = processTemplate(cptId, cptJsonSchemaNew); - int code = errorCode.getCode(); - if (code != ErrorCode.SUCCESS.getCode()) { - logger.error("[updateCpt] save credential template failed. errorcode:{} ", code); - return new ResponseData(null, ErrorCode.TRANSACTION_TIMEOUT); - } - return response; - } catch (TimeoutException e) { - logger.error("[updateCpt] transaction execute with timeout exception. ", e); - return new ResponseData(null, ErrorCode.TRANSACTION_TIMEOUT); - } catch (InterruptedException | ExecutionException e) { - logger.error("[updateCpt] transaction execute with exception. ", e); - return new ResponseData(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } - } - - private ErrorCode processTemplate(Integer cptId, String cptJsonSchemaNew) { - - if (!CredentialPojoUtils.isZkpCpt(cptJsonSchemaNew)) { - return ErrorCode.SUCCESS; - } - List attributeList; - try { - attributeList = JsonUtil.extractCptProperties(cptJsonSchemaNew); - - IssuerResult issuerResult = IssuerClient.makeCredentialTemplate(attributeList); - CredentialTemplateEntity template = issuerResult.credentialTemplateEntity; - String templateSecretKey = issuerResult.templateSecretKey; - ResponseData resp = - this.getDataDriver().addOrUpdate( - DataDriverConstant.DOMAIN_ISSUER_TEMPLATE_SECRET, - String.valueOf(cptId), - templateSecretKey); - if (resp.getErrorCode().intValue() != ErrorCode.SUCCESS.getCode()) { - logger.error("[processTemplate] save credential template to db failed."); - throw new DatabaseException("database error!"); - } - TransactionReceipt receipt = cptController.putCredentialTemplate( - DataToolUtils.intToUint256(cptId), - DataToolUtils - .stringToDynamicBytes(template.getPublicKey().getCredentialPublicKey()), - DataToolUtils.stringToDynamicBytes(template.getCredentialKeyCorrectnessProof())) - .get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS); - } catch (Exception e) { - logger.error("[processTemplate] process credential template failed.", e); - return ErrorCode.CPT_CREDENTIAL_TEMPLATE_SAVE_ERROR; - } - return ErrorCode.SUCCESS; - } - - /* (non-Javadoc) - * @see com.webank.weid.service.impl.engine.CptEngineController#queryCpt(int) - */ - @Override - public ResponseData queryCpt(int cptId) { - try { - - List typeList = cptController - .queryCpt(DataToolUtils.intToUint256(cptId)) - .get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS); - - if (typeList == null || typeList.isEmpty()) { - logger.error("Query cpt id : {} does not exist, result is null.", cptId); - return new ResponseData<>(null, ErrorCode.CPT_NOT_EXISTS); - } - - if (WeIdConstant.EMPTY_ADDRESS.equals(((Address) typeList.get(0)).toString())) { - logger.error("Query cpt id : {} does not exist.", cptId); - return new ResponseData<>(null, ErrorCode.CPT_NOT_EXISTS); - } - Cpt cpt = new Cpt(); - cpt.setCptId(cptId); - cpt.setCptPublisher( - WeIdUtils.convertAddressToWeId(((Address) typeList.get(0)).toString()) - ); - - long[] longArray = DataToolUtils.int256DynamicArrayToLongArray( - (DynamicArray) typeList.get(1) - ); - cpt.setCptVersion((int) longArray[0]); - cpt.setCreated(longArray[1]); - cpt.setUpdated(longArray[2]); - - String jsonSchema = DataToolUtils.bytes32DynamicArrayToStringWithoutTrim( - (DynamicArray) typeList.get(3)); - - Map jsonSchemaMap = DataToolUtils - .deserialize(jsonSchema.toString().trim(), HashMap.class); - cpt.setCptJsonSchema(jsonSchemaMap); - - int v = DataToolUtils.uint8ToInt((Uint8) typeList.get(4)); - byte[] r = DataToolUtils.bytes32ToBytesArray((Bytes32) typeList.get(5)); - byte[] s = DataToolUtils.bytes32ToBytesArray((Bytes32) typeList.get(6)); - Sign.SignatureData signatureData = DataToolUtils - .rawSignatureDeserialization(v, r, s); - String cptSignature = - new String( - DataToolUtils.base64Encode( - DataToolUtils.simpleSignatureSerialization(signatureData) - ), - StandardCharsets.UTF_8 - ); - cpt.setCptSignature(cptSignature); - return new ResponseData(cpt, ErrorCode.SUCCESS); - } catch (InterruptedException | ExecutionException e) { - logger.error("query cpt failed. Error message :{}", e); - return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } catch (TimeoutException e) { - return new ResponseData<>(null, ErrorCode.TRANSACTION_TIMEOUT); - } - } - - /* (non-Javadoc) - * @see com.webank.weid.service.impl.engine.CptServiceEngine#queryCredentialTemplate( - * java.lang.Integer) - */ - @Override - public ResponseData queryCredentialTemplate(Integer cptId) { - - CredentialTemplateEntity credentialTemplateStorage = new CredentialTemplateEntity(); - Future f = cptController - .getCredentialTemplateBlock(DataToolUtils.intToUint256(cptId)); - EthBlock latestBlock = null; - int blockNum = 0; - try { - blockNum = f.get().getValue().intValue(); - latestBlock = - ((Web3j) getWeb3j()) - .ethGetBlockByNumber( - new DefaultBlockParameterNumber(blockNum), - true - ) - .send(); - } catch (IOException | InterruptedException | ExecutionException e) { - logger.error( - "[queryCredentialTemplate]:get block by number :{} failed. Exception message:{}", - blockNum, - e - ); - } - if (latestBlock == null) { - logger.info( - "[queryCredentialTemplate]:get block by number :{} . latestBlock is null", - blockNum - ); - return new ResponseData(null, ErrorCode.UNKNOW_ERROR); - } - List transList = - latestBlock - .getBlock() - .getTransactions() - .stream() - .map(transactionResult -> (Transaction) transactionResult.get()) - .collect(Collectors.toList()); - - try { - for (Transaction transaction : transList) { - String transHash = transaction.getHash(); - - EthGetTransactionReceipt rec1 = ((Web3j) getWeb3j()) - .ethGetTransactionReceipt(transHash) - .send(); - TransactionReceipt receipt = rec1.getTransactionReceipt().get(); - List logs = rec1.getResult().getLogs(); - for (Log log : logs) { - String topic = log.getTopics().get(0); - if (StringUtils.equals(topic, CREDENTIALTEMPLATETOPIC)) { - List events = CptController - .getCredentialTemplateEvents(receipt); - CredentialTemplateEventResponse eventResp = events.get(0); - String credentialProof = eventResp.credentialProof.getTypeAsString(); - String pubKey = eventResp.credentialPublicKey.getTypeAsString(); - credentialTemplateStorage.setCredentialKeyCorrectnessProof(credentialProof); - TemplatePublicKey publicKey = TemplatePublicKey.newBuilder() - .setCredentialPublicKey(pubKey).build(); - credentialTemplateStorage.setPublicKey(publicKey); - } - } - } - } catch (IOException | DataTypeCastException e) { - logger.error( - "[queryCredentialTemplate]: get TransactionReceipt by cpt :{} failed.", - cptId, - e - ); - throw new ResolveAttributeException( - ErrorCode.TRANSACTION_EXECUTE_ERROR.getCode(), - ErrorCode.TRANSACTION_EXECUTE_ERROR.getCodeDesc()); - } - return new ResponseData(credentialTemplateStorage, - ErrorCode.SUCCESS); - } -} diff --git a/src/main/java/com/webank/weid/service/impl/engine/fiscov1/EvidenceServiceEngineV1.java b/src/main/java/com/webank/weid/service/impl/engine/fiscov1/EvidenceServiceEngineV1.java deleted file mode 100644 index 96075503b..000000000 --- a/src/main/java/com/webank/weid/service/impl/engine/fiscov1/EvidenceServiceEngineV1.java +++ /dev/null @@ -1,415 +0,0 @@ -/* - * Copyright© (2018-2020) WeBank Co., Ltd. - * - * This file is part of weid-java-sdk. - * - * weid-java-sdk is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * weid-java-sdk is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with weid-java-sdk. If not, see . - */ - -package com.webank.weid.service.impl.engine.fiscov1; - -import java.io.IOException; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.bcos.web3j.abi.datatypes.Utf8String; -import org.bcos.web3j.abi.datatypes.generated.Uint256; -import org.bcos.web3j.protocol.Web3j; -import org.bcos.web3j.protocol.core.DefaultBlockParameterNumber; -import org.bcos.web3j.protocol.core.methods.response.EthBlock; -import org.bcos.web3j.protocol.core.methods.response.EthGetTransactionReceipt; -import org.bcos.web3j.protocol.core.methods.response.Log; -import org.bcos.web3j.protocol.core.methods.response.Transaction; -import org.bcos.web3j.protocol.core.methods.response.TransactionReceipt; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.webank.weid.constant.ErrorCode; -import com.webank.weid.constant.ResolveEventLogStatus; -import com.webank.weid.constant.WeIdConstant; -import com.webank.weid.contract.v1.EvidenceContract; -import com.webank.weid.contract.v1.EvidenceContract.EvidenceAttributeChangedEventResponse; -import com.webank.weid.protocol.base.EvidenceInfo; -import com.webank.weid.protocol.base.EvidenceSignInfo; -import com.webank.weid.protocol.response.ResolveEventLogResult; -import com.webank.weid.protocol.response.ResponseData; -import com.webank.weid.protocol.response.TransactionInfo; -import com.webank.weid.service.impl.engine.BaseEngine; -import com.webank.weid.service.impl.engine.EvidenceServiceEngine; -import com.webank.weid.util.DataToolUtils; -import com.webank.weid.util.WeIdUtils; - -/** - * EvidenceServiceEngineV1 calls the evidence contract which runs on FISCO BCOS 1.3.x version. - * - * @author yanggang, chaoxinhu - */ -public class EvidenceServiceEngineV1 extends BaseEngine implements EvidenceServiceEngine { - - private static final Logger logger = LoggerFactory.getLogger(EvidenceServiceEngineV1.class); - - private static EvidenceContract evidenceContract; - - /** - * 构造函数. - */ - public EvidenceServiceEngineV1() { - if (evidenceContract == null) { - reload(); - } - } - - /** - * 重新加载静态合约对象. - */ - public void reload() { - evidenceContract = getContractService( - fiscoConfig.getEvidenceAddress(), - EvidenceContract.class); - } - - - @Override - public ResponseData> batchCreateEvidence( - List hashValues, - List signatures, - List logs, - List timestamp, - List signers, - String privateKey - ) { - return new ResponseData<>(null, ErrorCode.FISCO_BCOS_VERSION_NOT_SUPPORTED); - } - - @Override - public ResponseData createEvidence( - String hashValue, - String signature, - String extra, - Long timestamp, - String privateKey - ) { - try { - EvidenceContract evidenceContractWriter = - reloadContract( - fiscoConfig.getEvidenceAddress(), - privateKey, - EvidenceContract.class - ); - TransactionReceipt receipt = - evidenceContractWriter.createEvidence( - new Utf8String(hashValue), - new Utf8String(signature), - new Utf8String(extra), - new Uint256(new BigInteger(String.valueOf(timestamp), 10)) - ).get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS); - - TransactionInfo info = new TransactionInfo(receipt); - List eventList = - EvidenceContract.getEvidenceAttributeChangedEvents(receipt); - if (eventList == null || eventList.isEmpty()) { - return new ResponseData<>(StringUtils.EMPTY, - ErrorCode.CREDENTIAL_EVIDENCE_BASE_ERROR, info); - } else { - String address = WeIdUtils - .convertWeIdToAddress(DataToolUtils.convertPrivateKeyToDefaultWeId(privateKey)); - for (EvidenceAttributeChangedEventResponse event : eventList) { - if (isSignEvent(event) && event.value.getValue().equalsIgnoreCase(signature) - && event.signer.toString().equalsIgnoreCase(address)) { - return new ResponseData<>(hashValue, ErrorCode.SUCCESS, info); - } - } - } - return new ResponseData<>(StringUtils.EMPTY, - ErrorCode.CREDENTIAL_EVIDENCE_CONTRACT_FAILURE_ILLEAGAL_INPUT); - } catch (Exception e) { - logger.error("create evidence failed due to system error. ", e); - return new ResponseData<>(StringUtils.EMPTY, ErrorCode.CREDENTIAL_EVIDENCE_BASE_ERROR); - } - } - - @Override - public ResponseData addLog( - String hashValue, - String log, - Long timestamp, - String privateKey - ) { - try { - EvidenceContract evidenceContractWriter = - reloadContract( - fiscoConfig.getEvidenceAddress(), - privateKey, - EvidenceContract.class - ); - TransactionReceipt receipt = - evidenceContractWriter.setAttribute( - new Utf8String(hashValue), - new Utf8String("extra"), - new Utf8String(log), - new Uint256(new BigInteger(String.valueOf(timestamp), 10)) - ).get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS); - TransactionInfo info = new TransactionInfo(receipt); - List eventList = - EvidenceContract.getEvidenceAttributeChangedEvents(receipt); - if (eventList == null || eventList.isEmpty()) { - return new ResponseData<>(false, - ErrorCode.CREDENTIAL_EVIDENCE_BASE_ERROR, info); - } else { - String address = WeIdUtils - .convertWeIdToAddress(DataToolUtils.convertPrivateKeyToDefaultWeId(privateKey)); - for (EvidenceAttributeChangedEventResponse event : eventList) { - if (isExtraEvent(event) && event.value.getValue().equalsIgnoreCase(log) - && event.signer.toString().equalsIgnoreCase(address)) { - return new ResponseData<>(true, ErrorCode.SUCCESS, info); - } - } - } - return new ResponseData<>(false, - ErrorCode.CREDENTIAL_EVIDENCE_CONTRACT_FAILURE_ILLEAGAL_INPUT); - } catch (Exception e) { - logger.error("add log failed due to system error. ", e); - return new ResponseData<>(false, ErrorCode.CREDENTIAL_EVIDENCE_BASE_ERROR); - } - } - - @Override - public ResponseData getHashByCustomKey(String customKey) { - return new ResponseData(null, ErrorCode.FISCO_BCOS_VERSION_NOT_SUPPORTED); - } - - private static boolean isSignEvent(EvidenceAttributeChangedEventResponse event) { - return event.key.getValue().equalsIgnoreCase("info"); - } - - private static boolean isExtraEvent(EvidenceAttributeChangedEventResponse event) { - return event.key.getValue().equalsIgnoreCase("extra"); - } - - /** - * Get an evidence full info. - * - * @param hash evidence hash - * @return evidence info - */ - @Override - public ResponseData getInfo(String hash) { - EvidenceInfo evidenceInfo = new EvidenceInfo(); - evidenceInfo.setCredentialHash(hash); - int latestBlockNumber = 0; - try { - latestBlockNumber = DataToolUtils - .uint256ToInt(evidenceContract.getLatestRelatedBlock(new Utf8String(hash)) - .get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS)); - if (latestBlockNumber == 0) { - return new ResponseData<>(null, ErrorCode.CREDENTIAL_EVIDENCE_NOT_EXIST); - } - resolveTransaction(hash, latestBlockNumber, evidenceInfo); - // Reverse the order of the list - for (String signer : evidenceInfo.getSigners()) { - Collections.reverse(evidenceInfo.getSignInfo().get(signer).getLogs()); - } - return new ResponseData<>(evidenceInfo, ErrorCode.SUCCESS); - } catch (Exception e) { - logger.error("get evidence failed.", e); - return new ResponseData<>(null, ErrorCode.CREDENTIAL_EVIDENCE_BASE_ERROR); - } - } - - private static void resolveTransaction( - String hash, - int startBlockNumber, - EvidenceInfo evidenceInfo) { - - int previousBlock = startBlockNumber; - while (previousBlock != 0) { - int currentBlockNumber = previousBlock; - EthBlock latestBlock = null; - try { - latestBlock = ((Web3j) getWeb3j()).ethGetBlockByNumber( - new DefaultBlockParameterNumber(currentBlockNumber), true).send(); - } catch (IOException e) { - logger.error( - "Get block by number:{} failed. Exception message:{}", currentBlockNumber, e); - } - if (latestBlock == null) { - logger.info("Get block by number:{}. latestBlock is null", currentBlockNumber); - return; - } - List transList = latestBlock - .getBlock() - .getTransactions() - .stream() - .map(transactionResult -> (Transaction) transactionResult.get()) - .collect(Collectors.toList()); - previousBlock = 0; - try { - for (Transaction transaction : transList) { - String transHash = transaction.getHash(); - - EthGetTransactionReceipt rec1 = ((Web3j) getWeb3j()) - .ethGetTransactionReceipt(transHash) - .send(); - TransactionReceipt receipt = rec1.getTransactionReceipt().get(); - List logs = rec1.getResult().getLogs(); - Set topicSet = new HashSet<>(); - for (Log log : logs) { - if (topicSet.contains(log.getTopics().get(0))) { - continue; - } else { - topicSet.add(log.getTopics().get(0)); - } - ResolveEventLogResult returnValue = - resolveEventLog(hash, log, receipt, evidenceInfo); - if (returnValue.getResultStatus().equals( - ResolveEventLogStatus.STATUS_SUCCESS)) { - if (returnValue.getPreviousBlock() == currentBlockNumber) { - continue; - } - previousBlock = returnValue.getPreviousBlock(); - } - } - } - } catch (Exception e) { - logger.error("Get TransactionReceipt by key :{} failed.", hash, e); - } - } - } - - private static ResolveEventLogResult resolveEventLog( - String hash, - Log log, - TransactionReceipt receipt, - EvidenceInfo evidenceInfo) { - String topic = log.getTopics().get(0); - if (!StringUtils.isBlank(topic)) { - return resolveAttributeEvent(hash, receipt, evidenceInfo); - } - ResolveEventLogResult response = new ResolveEventLogResult(); - response.setResolveEventLogStatus(ResolveEventLogStatus.STATUS_EVENT_NULL); - return response; - } - - private static ResolveEventLogResult resolveAttributeEvent( - String hash, - TransactionReceipt receipt, - EvidenceInfo evidenceInfo) { - List eventList = - EvidenceContract.getEvidenceAttributeChangedEvents(receipt); - ResolveEventLogResult response = new ResolveEventLogResult(); - - if (CollectionUtils.isEmpty(eventList)) { - response.setResolveEventLogStatus(ResolveEventLogStatus.STATUS_EVENTLOG_NULL); - return response; - } - - int previousBlock = 0; - // Actual construction code - for (EvidenceAttributeChangedEventResponse event : eventList) { - if (event.signer == null || event.key == null || event.previousBlock == null) { - response.setResolveEventLogStatus(ResolveEventLogStatus.STATUS_RES_NULL); - return response; - } - if (!hash.equalsIgnoreCase(event.hash.getValue())) { - response.setResolveEventLogStatus(ResolveEventLogStatus.STATUS_KEY_NOT_MATCH); - return response; - } - String signerWeId = WeIdUtils.convertAddressToWeId(event.signer.toString()); - if (isSignEvent(event)) { - // higher block sig will be overwritten anyway - any new one will be accepted - EvidenceSignInfo signInfo = new EvidenceSignInfo(); - signInfo.setSignature(event.value.getValue()); - signInfo.setTimestamp(String.valueOf(DataToolUtils.uint256ToInt(event.updated))); - if (evidenceInfo.getSignInfo().containsKey(signerWeId)) { - signInfo.setLogs( - evidenceInfo.getSignInfo().get(signerWeId).getLogs()); - } - evidenceInfo.getSignInfo().put(signerWeId, signInfo); - } - if (isExtraEvent(event) && !StringUtils.isEmpty(event.value.getValue())) { - // higher block blob will overwrite existing one - any new one will be abandoned - EvidenceSignInfo signInfo = new EvidenceSignInfo(); - if (evidenceInfo.getSignInfo().containsKey(signerWeId)) { - signInfo.setSignature( - evidenceInfo.getSignInfo().get(signerWeId).getSignature()); - signInfo.setTimestamp( - evidenceInfo.getSignInfo().get(signerWeId).getTimestamp()); - } else { - signInfo.setSignature(StringUtils.EMPTY); - signInfo.setTimestamp(StringUtils.EMPTY); - } - List extraList = - evidenceInfo.getSignInfo().get(signerWeId).getLogs(); - extraList.add(event.value.getValue()); - signInfo.setLogs(extraList); - evidenceInfo.getSignInfo().put(signerWeId, signInfo); - } - previousBlock = DataToolUtils.uint256ToInt(event.previousBlock); - } - response.setPreviousBlock(previousBlock); - response.setResolveEventLogStatus(ResolveEventLogStatus.STATUS_SUCCESS); - return response; - } - - - /* (non-Javadoc) - * @see com.webank.weid.service.impl.engine - * .EvidenceServiceEngine#createEvidenceWithLogAndCustomKey( - * java.lang.String, java.lang.String, java.lang.String, java.lang.Long, java.lang.String, - * java.lang.String) - */ - @Override - public ResponseData createEvidenceWithCustomKey( - String hashValue, - String signature, - String extra, - Long timestamp, - String extraKey, - String privateKey) { - - return new ResponseData(null, ErrorCode.FISCO_BCOS_VERSION_NOT_SUPPORTED); - } - - @Override - public ResponseData> batchCreateEvidenceWithCustomKey( - List hashValues, - List signatures, - List logs, - List timestamps, - List signers, - List customKeys, - String privateKey - ) { - return new ResponseData<>(null, ErrorCode.FISCO_BCOS_VERSION_NOT_SUPPORTED); - } - - - /* (non-Javadoc) - * @see com.webank.weid.service.impl.engine.EvidenceServiceEngine#getInfoByCustomKey( - * java.lang.String) - */ - @Override - public ResponseData getInfoByCustomKey(String extraKey) { - - return new ResponseData(null, ErrorCode.FISCO_BCOS_VERSION_NOT_SUPPORTED); - } -} diff --git a/src/main/java/com/webank/weid/service/impl/engine/fiscov1/RawTransactionServiceEngineV1.java b/src/main/java/com/webank/weid/service/impl/engine/fiscov1/RawTransactionServiceEngineV1.java deleted file mode 100644 index bcba31538..000000000 --- a/src/main/java/com/webank/weid/service/impl/engine/fiscov1/RawTransactionServiceEngineV1.java +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Copyright© (2018-2019) WeBank Co., Ltd. - * - * This file is part of weid-java-sdk. - * - * weid-java-sdk is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * weid-java-sdk is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with weid-java-sdk. If not, see . - */ - -package com.webank.weid.service.impl.engine.fiscov1; - -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.bcos.web3j.protocol.Web3j; -import org.bcos.web3j.protocol.core.methods.response.EthGetTransactionReceipt; -import org.bcos.web3j.protocol.core.methods.response.EthSendTransaction; -import org.bcos.web3j.protocol.core.methods.response.TransactionReceipt; -import org.bcos.web3j.protocol.exceptions.TransactionTimeoutException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.webank.weid.constant.ErrorCode; -import com.webank.weid.constant.WeIdConstant; -import com.webank.weid.contract.v1.AuthorityIssuerController; -import com.webank.weid.contract.v1.AuthorityIssuerController.AuthorityIssuerRetLogEventResponse; -import com.webank.weid.contract.v1.CptController; -import com.webank.weid.contract.v1.CptController.RegisterCptRetLogEventResponse; -import com.webank.weid.contract.v1.WeIdContract; -import com.webank.weid.contract.v1.WeIdContract.WeIdAttributeChangedEventResponse; -import com.webank.weid.protocol.base.CptBaseInfo; -import com.webank.weid.protocol.response.ResponseData; -import com.webank.weid.service.impl.RawTransactionServiceImpl; -import com.webank.weid.service.impl.engine.BaseEngine; -import com.webank.weid.service.impl.engine.RawTransactionServiceEngine; -import com.webank.weid.util.DataToolUtils; -import com.webank.weid.util.TransactionUtils; - -/** - * awTransactionService runs on FISCO BCOS 1.3.x. - * - * @author tonychen 2019年6月26日 - */ -public class RawTransactionServiceEngineV1 extends BaseEngine implements - RawTransactionServiceEngine { - - private static final Logger logger = LoggerFactory.getLogger(RawTransactionServiceImpl.class); - - /** - * 此方法不需要加载合约对象. - */ - public void reload() { - logger.info("[reload] nothing to do for reload."); - } - - - /** - * Verify Authority Issuer related events. - * - * @param event the Event - * @param opcode the Opcode - * @return the ErrorCode - */ - public static ErrorCode verifyAuthorityIssuerRelatedEvent( - AuthorityIssuerRetLogEventResponse event, - Integer opcode) { - if (event == null) { - return ErrorCode.ILLEGAL_INPUT; - } - if (event.addr == null || event.operation == null || event.retCode == null) { - return ErrorCode.ILLEGAL_INPUT; - } - Integer eventOpcode = event.operation.getValue().intValue(); - if (eventOpcode.equals(opcode)) { - Integer eventRetCode = event.retCode.getValue().intValue(); - return ErrorCode.getTypeByErrorCode(eventRetCode); - } else { - return ErrorCode.AUTHORITY_ISSUER_OPCODE_MISMATCH; - } - } - - /** - * Send a transaction to blockchain through web3j instance using the transactionHex value. - * - * @param transactionHex the transactionHex value - * @return the transactionReceipt - * @throws Exception the exception - */ - public static TransactionReceipt sendTransaction(String transactionHex) - throws Exception { - Web3j web3j = (Web3j) getWeb3j(); - EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(transactionHex) - .sendAsync().get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS); - if (ethSendTransaction.hasError()) { - logger.error("Error processing transaction request: " - + ethSendTransaction.getError().getMessage()); - return null; - } - Optional receiptOptional = - getTransactionReceiptRequest(web3j, ethSendTransaction.getTransactionHash()); - int sumTime = 0; - try { - for (int i = 0; i < WeIdConstant.POLL_TRANSACTION_ATTEMPTS; i++) { - if (!receiptOptional.isPresent()) { - Thread.sleep((long) WeIdConstant.POLL_TRANSACTION_SLEEP_DURATION); - sumTime += WeIdConstant.POLL_TRANSACTION_SLEEP_DURATION; - receiptOptional = getTransactionReceiptRequest(web3j, - ethSendTransaction.getTransactionHash()); - } else { - return receiptOptional.get(); - } - } - } catch (Exception e) { - throw new TransactionTimeoutException("Transaction receipt was not generated after " - + ((sumTime) / 1000 - + " seconds for transaction: " + ethSendTransaction)); - } - return null; - } - - /** - * Get a TransactionReceipt request from a transaction Hash. - * - * @param web3j the web3j instance to blockchain - * @param transactionHash the transactionHash value - * @return the transactionReceipt wrapper - * @throws Exception the exception - */ - private static Optional getTransactionReceiptRequest(Web3j web3j, - String transactionHash) throws Exception { - - EthGetTransactionReceipt transactionReceipt = - web3j.ethGetTransactionReceipt(transactionHash).send(); - if (transactionReceipt.hasError()) { - logger.error("Error processing transaction request: " - + transactionReceipt.getError().getMessage()); - return Optional.empty(); - } - return transactionReceipt.getTransactionReceipt(); - } - - /** - * Verify Register CPT related events. - * - * @param transactionReceipt the TransactionReceipt - * @return the ErrorCode - */ - public static ResponseData resolveRegisterCptEvents( - TransactionReceipt transactionReceipt) { - - List event = CptController.getRegisterCptRetLogEvents( - transactionReceipt - ); - - if (CollectionUtils.isEmpty(event)) { - logger.error("[registerCpt] event is empty"); - return new ResponseData<>(null, ErrorCode.CPT_EVENT_LOG_NULL); - } - - return TransactionUtils.getResultByResolveEvent( - event.get(0).retCode, - event.get(0).cptId, - event.get(0).cptVersion, - transactionReceipt - ); - } - - /** - * Create a WeIdentity DID from the provided public key, with preset transaction hex value. - * - * @param transactionHex the transaction hex value - * @return Error message if any - */ - @Override - public ResponseData createWeId(String transactionHex) { - - try { - TransactionReceipt transactionReceipt = sendTransaction(transactionHex); - List response = - WeIdContract.getWeIdAttributeChangedEvents(transactionReceipt); - if (!CollectionUtils.isEmpty(response)) { - return new ResponseData<>(Boolean.TRUE.toString(), ErrorCode.SUCCESS); - } - } catch (Exception e) { - logger.error("[createWeId] create failed due to unknown transaction error. ", e); - } - return new ResponseData<>(StringUtils.EMPTY, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } - - /** - * Register a new Authority Issuer on Chain with preset transaction hex value. The inputParam is - * a Json String, with two keys: WeIdentity DID and Name. Parameters will be ordered as - * mentioned after validity check; then transactionHex will be sent to blockchain. - * - * @param transactionHex the transaction hex value - * @return true if succeeds, false otherwise - */ - @Override - public ResponseData registerAuthorityIssuer(String transactionHex) { - - try { - TransactionReceipt transactionReceipt = sendTransaction(transactionHex); - - List eventList = - AuthorityIssuerController.getAuthorityIssuerRetLogEvents(transactionReceipt); - AuthorityIssuerRetLogEventResponse event = eventList.get(0); - ErrorCode errorCode = verifyAuthorityIssuerRelatedEvent(event, - WeIdConstant.ADD_AUTHORITY_ISSUER_OPCODE); - Boolean result = errorCode.getCode() == ErrorCode.SUCCESS.getCode(); - return new ResponseData<>(result.toString(), errorCode); - } catch (Exception e) { - logger.error("[registerAuthorityIssuer] register failed due to transaction error.", e); - } - return new ResponseData<>(StringUtils.EMPTY, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } - - /** - * Register a new CPT to the blockchain with preset transaction hex value. - * - * @param transactionHex the transaction hex value - * @return The registered CPT info - */ - public ResponseData registerCpt(String transactionHex) { - - try { - TransactionReceipt transactionReceipt = sendTransaction(transactionHex); - CptBaseInfo cptBaseInfo = resolveRegisterCptEvents(transactionReceipt) - .getResult(); - - if (cptBaseInfo != null) { - return new ResponseData<>(DataToolUtils.objToJsonStrWithNoPretty(cptBaseInfo), - ErrorCode.SUCCESS); - } - } catch (Exception e) { - logger.error("[registerCpt] register failed due to unknown transaction error. ", e); - } - return new ResponseData<>(StringUtils.EMPTY, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } -} diff --git a/src/main/java/com/webank/weid/service/impl/engine/fiscov1/WeIdServiceEngineV1.java b/src/main/java/com/webank/weid/service/impl/engine/fiscov1/WeIdServiceEngineV1.java deleted file mode 100644 index 017ee811f..000000000 --- a/src/main/java/com/webank/weid/service/impl/engine/fiscov1/WeIdServiceEngineV1.java +++ /dev/null @@ -1,589 +0,0 @@ -/* - * Copyright© (2018-2019) WeBank Co., Ltd. - * - * This file is part of weid-java-sdk. - * - * weid-java-sdk is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * weid-java-sdk is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with weid-java-sdk. If not, see . - */ - -package com.webank.weid.service.impl.engine.fiscov1; - -import java.io.IOException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.stream.Collectors; - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.bcos.web3j.abi.EventEncoder; -import org.bcos.web3j.abi.TypeReference; -import org.bcos.web3j.abi.datatypes.Address; -import org.bcos.web3j.abi.datatypes.Bool; -import org.bcos.web3j.abi.datatypes.DynamicBytes; -import org.bcos.web3j.abi.datatypes.Event; -import org.bcos.web3j.abi.datatypes.generated.Bytes32; -import org.bcos.web3j.abi.datatypes.generated.Int256; -import org.bcos.web3j.abi.datatypes.generated.Uint256; -import org.bcos.web3j.protocol.Web3j; -import org.bcos.web3j.protocol.core.DefaultBlockParameterNumber; -import org.bcos.web3j.protocol.core.methods.response.EthBlock; -import org.bcos.web3j.protocol.core.methods.response.EthGetTransactionReceipt; -import org.bcos.web3j.protocol.core.methods.response.Log; -import org.bcos.web3j.protocol.core.methods.response.Transaction; -import org.bcos.web3j.protocol.core.methods.response.TransactionReceipt; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.webank.weid.constant.ErrorCode; -import com.webank.weid.constant.ResolveEventLogStatus; -import com.webank.weid.constant.WeIdConstant; -import com.webank.weid.contract.v1.WeIdContract; -import com.webank.weid.contract.v1.WeIdContract.WeIdAttributeChangedEventResponse; -import com.webank.weid.exception.DataTypeCastException; -import com.webank.weid.exception.ResolveAttributeException; -import com.webank.weid.protocol.base.AuthenticationProperty; -import com.webank.weid.protocol.base.PublicKeyProperty; -import com.webank.weid.protocol.base.ServiceProperty; -import com.webank.weid.protocol.base.WeIdDocument; -import com.webank.weid.protocol.base.WeIdPojo; -import com.webank.weid.protocol.response.ResolveEventLogResult; -import com.webank.weid.protocol.response.ResponseData; -import com.webank.weid.protocol.response.TransactionInfo; -import com.webank.weid.service.impl.engine.BaseEngine; -import com.webank.weid.service.impl.engine.WeIdServiceEngine; -import com.webank.weid.util.DataToolUtils; -import com.webank.weid.util.DateUtils; -import com.webank.weid.util.WeIdUtils; - -/** - * WeIdServiceEngine calls the weid contract which runs on FISCO BCOS 1.3.x version. - * - * @author tonychen 2019年6月21日 - */ -public class WeIdServiceEngineV1 extends BaseEngine implements WeIdServiceEngine { - - /** - * Block number for stopping parsing. - */ - private static final int STOP_RESOLVE_BLOCK_NUMBER = 0; - /** - * WeIdentity DID contract address. - */ - - private static final Logger logger = LoggerFactory.getLogger(WeIdServiceEngineV1.class); - /** - * The topic map. - */ - private static final HashMap topicMap; - /** - * WeIdentity DID contract object, for calling weIdentity DID contract. - */ - private static WeIdContract weIdContract; - - static { - // initialize the event topic - topicMap = new HashMap(); - final Event event = - new Event( - WeIdConstant.WEID_EVENT_ATTRIBUTE_CHANGE, - Arrays.>asList(new TypeReference
() { - }), - Arrays.>asList( - new TypeReference() { - }, - new TypeReference() { - }, - new TypeReference() { - }, - new TypeReference() { - }) - ); - topicMap.put( - EventEncoder.encode(event), - WeIdConstant.WEID_EVENT_ATTRIBUTE_CHANGE - ); - } - - /** - * 构造函数. - */ - public WeIdServiceEngineV1() { - if (weIdContract == null) { - reload(); - } - } - - private static ResolveEventLogResult resolveAttributeEvent( - String weId, - TransactionReceipt receipt, - WeIdDocument result) { - - List eventlog = - WeIdContract.getWeIdAttributeChangedEvents(receipt); - ResolveEventLogResult response = new ResolveEventLogResult(); - - if (CollectionUtils.isEmpty(eventlog)) { - response.setResolveEventLogStatus(ResolveEventLogStatus.STATUS_EVENTLOG_NULL); - return response; - } - - int previousBlock = 0; - for (WeIdAttributeChangedEventResponse res : eventlog) { - if (res.identity == null || res.updated == null || res.previousBlock == null) { - response.setResolveEventLogStatus(ResolveEventLogStatus.STATUS_RES_NULL); - return response; - } - - String identity = res.identity.toString(); - if (result.getUpdated() == null) { - long timeStamp = res.updated.getValue().longValue(); - result.setUpdated(timeStamp); - } - String weAddress = WeIdUtils.convertWeIdToAddress(weId); - if (!StringUtils.equals(weAddress, identity)) { - response.setResolveEventLogStatus(ResolveEventLogStatus.STATUS_KEY_NOT_MATCH); - return response; - } - - String key = DataToolUtils.bytes32ToString(res.key); - String value = DataToolUtils.dynamicBytesToString(res.value); - previousBlock = res.previousBlock.getValue().intValue(); - buildupWeIdAttribute(key, value, weId, result); - } - - response.setPreviousBlock(previousBlock); - response.setResolveEventLogStatus(ResolveEventLogStatus.STATUS_SUCCESS); - return response; - } - - private static void buildupWeIdAttribute( - String key, String value, String weId, WeIdDocument result) { - if (StringUtils.startsWith(key, WeIdConstant.WEID_DOC_PUBLICKEY_PREFIX)) { - buildWeIdPublicKeys(value, weId, result); - } else if (StringUtils.startsWith(key, WeIdConstant.WEID_DOC_AUTHENTICATE_PREFIX)) { - buildWeIdPublicKeys(value, weId, result); - buildWeIdAuthentication(value, weId, result); - } else if (StringUtils.startsWith(key, WeIdConstant.WEID_DOC_SERVICE_PREFIX)) { - buildWeIdService(key, value, weId, result); - } else { - buildWeIdAttributeDefault(key, value, weId, result); - } - } - - private static void buildWeIdPublicKeys(String value, String weId, WeIdDocument result) { - - logger.info("method buildWeIdPublicKeys() parameter::value:{}, weId:{}, " - + "result:{}", value, weId, result); - List pubkeyList = result.getPublicKey(); - // Only store the latest public key - // OBSOLETE and non-OBSOLETE public keys are regarded as the same - String trimmedPubKey = StringUtils - .splitByWholeSeparator(value.replace( - WeIdConstant.REMOVED_PUBKEY_TAG, ""), WeIdConstant.SEPARATOR)[0]; - for (PublicKeyProperty pr : pubkeyList) { - if (pr.getPublicKey().contains(trimmedPubKey)) { - return; - } - } - PublicKeyProperty pubKey = new PublicKeyProperty(); - pubKey.setId( - new StringBuffer() - .append(weId) - .append("#keys-") - .append(result.getPublicKey().size()) - .toString() - ); - String[] publicKeyData = StringUtils.splitByWholeSeparator(value, WeIdConstant.SEPARATOR); - if (publicKeyData != null && publicKeyData.length == 2) { - pubKey.setPublicKey(publicKeyData[0]); - String weAddress = publicKeyData[1]; - String owner = WeIdUtils.convertAddressToWeId(weAddress); - pubKey.setOwner(owner); - } - result.getPublicKey().add(pubKey); - } - - private static void buildWeIdAuthentication(String value, String weId, WeIdDocument result) { - - logger.info("method buildWeIdAuthentication() parameter::value:{}, weId:{}, " - + "result:{}", value, weId, result); - AuthenticationProperty auth = new AuthenticationProperty(); - List keys = result.getPublicKey(); - List authList = result.getAuthentication(); - - // Firstly, if this is an obsolete auth, directly append it and return unless a same - // one exists; if this is a normal auth, then check whether there is an existing obsolete - // one. if so, return. if not, go down further. - if (value.contains(WeIdConstant.REMOVED_AUTHENTICATION_TAG)) { - for (AuthenticationProperty ap : authList) { - String pubKeyId = ap.getPublicKey(); - for (PublicKeyProperty pkp : keys) { - if (pubKeyId.equalsIgnoreCase(pkp.getId()) && value - .contains(pkp.getPublicKey())) { - return; - } - } - } - auth.setPublicKey(value); - result.getAuthentication().add(auth); - } else { - for (AuthenticationProperty ap : authList) { - if (ap.getPublicKey() - .replace(WeIdConstant.REMOVED_AUTHENTICATION_TAG, "") - .contains(value) && ap - .getPublicKey() - .contains(WeIdConstant.REMOVED_AUTHENTICATION_TAG)) { - return; - } - } - } - - for (PublicKeyProperty r : keys) { - if (StringUtils.contains(value, r.getPublicKey())) { - for (AuthenticationProperty ar : authList) { - if (StringUtils.equals(ar.getPublicKey(), r.getId())) { - return; - } - } - auth.setPublicKey(r.getId()); - result.getAuthentication().add(auth); - } - } - } - - private static void buildWeIdService(String key, String value, String weId, - WeIdDocument result) { - - logger.info("method buildWeIdService() parameter::key{}, value:{}, weId:{}, " - + "result:{}", key, value, weId, result); - String service = StringUtils.splitByWholeSeparator(key, "/")[2]; - List serviceList = result.getService(); - for (ServiceProperty sr : serviceList) { - if (StringUtils.equals(service, sr.getType())) { - return; - } - } - ServiceProperty serviceResult = new ServiceProperty(); - serviceResult.setType(service); - serviceResult.setServiceEndpoint(value); - result.getService().add(serviceResult); - } - - private static void buildWeIdAttributeDefault( - String key, String value, String weId, WeIdDocument result) { - - logger.info("method buildWeIdAttributeDefault() parameter::key{}, value:{}, weId:{}, " - + "result:{}", key, value, weId, result); - switch (key) { - case WeIdConstant.WEID_DOC_CREATED: - result.setCreated(Long.valueOf(value)); - break; - default: - break; - } - } - - private static ResolveEventLogResult resolveEventLog( - String weId, Log log, TransactionReceipt receipt, WeIdDocument result) { - String topic = log.getTopics().get(0); - String event = topicMap.get(topic); - - if (StringUtils.isNotBlank(event)) { - switch (event) { - case WeIdConstant.WEID_EVENT_ATTRIBUTE_CHANGE: - return resolveAttributeEvent(weId, receipt, result); - default: - } - } - ResolveEventLogResult response = new ResolveEventLogResult(); - response.setResolveEventLogStatus(ResolveEventLogStatus.STATUS_EVENT_NULL); - return response; - } - - private static void resolveTransaction( - String weId, - int blockNumber, - WeIdDocument result) { - - int previousBlock = blockNumber; - while (previousBlock != STOP_RESOLVE_BLOCK_NUMBER) { - int currentBlockNumber = previousBlock; - EthBlock latestBlock = null; - try { - latestBlock = - ((Web3j) getWeb3j()) - .ethGetBlockByNumber( - new DefaultBlockParameterNumber(currentBlockNumber), - true - ) - .send(); - } catch (IOException e) { - logger.error( - "[resolveTransaction]:get block by number :{} failed. Exception message:{}", - currentBlockNumber, - e - ); - } - if (latestBlock == null) { - logger.info( - "[resolveTransaction]:get block by number :{} . latestBlock is null", - currentBlockNumber - ); - return; - } - List transList = - latestBlock - .getBlock() - .getTransactions() - .stream() - .map(transactionResult -> (Transaction) transactionResult.get()) - .collect(Collectors.toList()); - - previousBlock = 0; - try { - for (Transaction transaction : transList) { - String transHash = transaction.getHash(); - - EthGetTransactionReceipt rec1 = ((Web3j) getWeb3j()) - .ethGetTransactionReceipt(transHash) - .send(); - TransactionReceipt receipt = rec1.getTransactionReceipt().get(); - List logs = rec1.getResult().getLogs(); - for (Log log : logs) { - ResolveEventLogResult returnValue = - resolveEventLog(weId, log, receipt, result); - if (returnValue.getResultStatus().equals( - ResolveEventLogStatus.STATUS_SUCCESS)) { - if (returnValue.getPreviousBlock() == currentBlockNumber) { - continue; - } - previousBlock = returnValue.getPreviousBlock(); - } - } - } - } catch (IOException | DataTypeCastException e) { - logger.error( - "[resolveTransaction]: get TransactionReceipt by weId :{} failed.", - weId, - e - ); - throw new ResolveAttributeException( - ErrorCode.TRANSACTION_EXECUTE_ERROR.getCode(), - ErrorCode.TRANSACTION_EXECUTE_ERROR.getCodeDesc()); - } - } - } - - /** - * 重新加载静态合约对象. - */ - public void reload() { - weIdContract = getContractService(fiscoConfig.getWeIdAddress(), WeIdContract.class); - } - - /* (non-Javadoc) - * @see com.webank.weid.service.impl.engine.WeIdController#isWeIdExist(java.lang.String) - */ - @Override - public ResponseData isWeIdExist(String weId) { - try { - Bool isExist = weIdContract - .isIdentityExist(new Address(WeIdUtils.convertWeIdToAddress(weId))) - .get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS); - Boolean result = isExist.getValue(); - return new ResponseData<>(result, ErrorCode.SUCCESS); - } catch (InterruptedException | ExecutionException e) { - logger.error("[isWeIdExist] execute failed. Error message :{}", e); - return new ResponseData<>(false, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } catch (TimeoutException e) { - logger.error("[isWeIdExist] execute with timeout. Error message :{}", e); - return new ResponseData<>(false, ErrorCode.TRANSACTION_TIMEOUT); - } catch (Exception e) { - logger.error("[isWeIdExist] execute failed. Error message :{}", e); - return new ResponseData<>(false, ErrorCode.UNKNOW_ERROR); - } - } - - /* (non-Javadoc) - * @see com.webank.weid.service.impl.engine.WeIdController#getWeIdDocument(java.lang.String) - */ - @Override - public ResponseData getWeIdDocument(String weId) { - WeIdDocument result = new WeIdDocument(); - result.setId(weId); - int latestBlockNumber = 0; - try { - String identityAddr = WeIdUtils.convertWeIdToAddress(weId); - latestBlockNumber = - weIdContract - .getLatestRelatedBlock(new Address(identityAddr)) - .get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS) - .getValue() - .intValue(); - if (0 == latestBlockNumber) { - return new ResponseData<>(null, ErrorCode.WEID_DOES_NOT_EXIST); - } - - resolveTransaction(weId, latestBlockNumber, result); - return new ResponseData<>(result, ErrorCode.SUCCESS); - } catch (InterruptedException | ExecutionException e) { - logger.error("Set weId service failed. Error message :{}", e); - return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } catch (TimeoutException e) { - logger.error("Set weId service timeout. Error message :{}", e); - return new ResponseData<>(null, ErrorCode.TRANSACTION_TIMEOUT); - } catch (ResolveAttributeException e) { - logger.error("[getWeIdDocument]: resolveTransaction failed. " - + "weId: {}, errorCode:{}", - weId, - e.getErrorCode(), - e); - return new ResponseData<>(null, ErrorCode.getTypeByErrorCode(e.getErrorCode())); - } catch (Exception e) { - logger.error("[getWeIdDocument]: exception.", e); - return new ResponseData<>(null, ErrorCode.UNKNOW_ERROR); - } - } - - - /* (non-Javadoc) - * @see com.webank.weid.service.impl.engine.WeIdController - * #createWeId(java.lang.String, java.lang.String, java.lang.String) - */ - @Override - - public ResponseData createWeId( - String weAddress, - String publicKey, - String privateKey, - boolean isDelegate) { - - WeIdContract weIdContract = (WeIdContract) reloadContract( - fiscoConfig.getWeIdAddress(), - privateKey, - WeIdContract.class); - try { - DynamicBytes auth = DataToolUtils.stringToDynamicBytes( - new StringBuffer() - .append(publicKey) - .append(WeIdConstant.SEPARATOR) - .append(weAddress) - .toString()); - DynamicBytes created = DataToolUtils - .stringToDynamicBytes(DateUtils.getNoMillisecondTimeStampString()); - - Future future = null; - if (isDelegate) { - return new ResponseData<>(false, ErrorCode.FISCO_BCOS_VERSION_NOT_SUPPORTED); - } else { - future = weIdContract.createWeId( - new Address(weAddress), - auth, - created, - DateUtils.getNoMillisecondTimeStampInt256() - ); - } - TransactionReceipt receipt = - future.get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS); - TransactionInfo info = new TransactionInfo(receipt); - List response = - WeIdContract.getWeIdAttributeChangedEvents(receipt); - - if (CollectionUtils.isEmpty(response)) { - logger.error( - "The input private key does not match the current weid, operation of " - + "modifying weid is not allowed. we address is {}", - weAddress - ); - return new ResponseData(false, - ErrorCode.WEID_PRIVATEKEY_DOES_NOT_MATCH, - info); - } - return new ResponseData(true, ErrorCode.SUCCESS, info); - } catch (InterruptedException | ExecutionException e) { - logger.error("Set public key failed. Error message :{}", e); - return new ResponseData(false, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } catch (TimeoutException e) { - logger.error("Set public key timeout. Error message :{}", e); - return new ResponseData(false, ErrorCode.TRANSACTION_TIMEOUT); - } - } - - - /* (non-Javadoc) - * @see com.webank.weid.service.impl.engine.WeIdController - * #setAttribute(java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public ResponseData setAttribute( - String weAddress, - String attributeKey, - String value, - String privateKey, - boolean isDelegate) { - - try { - WeIdContract weIdContract = (WeIdContract) reloadContract( - fiscoConfig.getWeIdAddress(), - privateKey, - WeIdContract.class); - Future future = null; - if (isDelegate) { - return new ResponseData<>(false, ErrorCode.FISCO_BCOS_VERSION_NOT_SUPPORTED); - } else { - future = - weIdContract.setAttribute( - new Address(weAddress), - DataToolUtils.stringToBytes32(attributeKey), - DataToolUtils.stringToDynamicBytes( - value), - DateUtils.getNoMillisecondTimeStampInt256() - ); - } - TransactionReceipt receipt = - future.get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS); - TransactionInfo info = new TransactionInfo(receipt); - List response = - WeIdContract.getWeIdAttributeChangedEvents(receipt); - if (CollectionUtils.isNotEmpty(response)) { - return new ResponseData(true, ErrorCode.SUCCESS, info); - } else { - return new ResponseData(false, - ErrorCode.WEID_PRIVATEKEY_DOES_NOT_MATCH, - info); - } - } catch (InterruptedException | ExecutionException e) { - logger.error("Set public key failed. Error message :{}", e); - return new ResponseData(false, ErrorCode.TRANSACTION_EXECUTE_ERROR); - } catch (TimeoutException e) { - logger.error("Set public key timeout. Error message :{}", e); - return new ResponseData(false, ErrorCode.TRANSACTION_TIMEOUT); - } - } - - @Override - public ResponseData> getWeIdList( - Integer blockNumber, - Integer pageSize, - Integer indexInBlock, - boolean direction - ) throws Exception { - return new ResponseData<>(null, ErrorCode.THIS_IS_UNSUPPORTED); - } -} 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 590b194d8..abdf0540e 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 @@ -23,7 +23,6 @@ import java.util.ArrayList; import java.util.List; -import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.fisco.bcos.web3j.abi.datatypes.Address; import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; 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 6df327610..bbf5bde3a 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 @@ -37,8 +37,8 @@ import com.webank.wedpr.selectivedisclosure.proto.TemplatePublicKey; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; -import org.bcos.web3j.crypto.Sign; import org.fisco.bcos.web3j.abi.EventEncoder; +import org.fisco.bcos.web3j.crypto.Sign; import org.fisco.bcos.web3j.protocol.Web3j; import org.fisco.bcos.web3j.protocol.core.DefaultBlockParameterNumber; import org.fisco.bcos.web3j.protocol.core.methods.response.BcosBlock; @@ -46,6 +46,7 @@ import org.fisco.bcos.web3j.protocol.core.methods.response.Log; import org.fisco.bcos.web3j.protocol.core.methods.response.Transaction; import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.fisco.bcos.web3j.tuples.generated.Tuple2; import org.fisco.bcos.web3j.tuples.generated.Tuple7; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -59,8 +60,11 @@ import com.webank.weid.contract.v2.CptController.RegisterCptRetLogEventResponse; import com.webank.weid.contract.v2.CptController.UpdateCptRetLogEventResponse; import com.webank.weid.exception.DatabaseException; +import com.webank.weid.protocol.base.ClaimPolicy; import com.webank.weid.protocol.base.Cpt; import com.webank.weid.protocol.base.CptBaseInfo; +import com.webank.weid.protocol.base.PresentationPolicyE; +import com.webank.weid.protocol.base.WeIdPrivateKey; import com.webank.weid.protocol.response.ResponseData; import com.webank.weid.protocol.response.RsvSignature; import com.webank.weid.service.impl.engine.BaseEngine; @@ -97,10 +101,11 @@ public CptServiceEngineV2() { reload(); } } - + /** * 重新加载静态合约对象. */ + @Override public void reload() { cptController = getContractService(fiscoConfig.getCptAddress(), CptController.class); } @@ -125,30 +130,50 @@ private static Persistence getDataDriver() { */ @Override public ResponseData updateCpt(int cptId, String address, String cptJsonSchemaNew, - RsvSignature rsvSignature, String privateKey) { + RsvSignature rsvSignature, String privateKey, int dataStorageIndex) { List byteArray = new ArrayList<>(); TransactionReceipt transactionReceipt; try { CptController cptController = reloadContract(fiscoConfig.getCptAddress(), privateKey, CptController.class); - transactionReceipt = cptController.updateCpt( - BigInteger.valueOf(Long.valueOf(cptId)), - address, - DataToolUtils.listToListBigInteger( - DataToolUtils.getParamCreatedList(WeIdConstant.CPT_LONG_ARRAY_LENGTH), - WeIdConstant.CPT_LONG_ARRAY_LENGTH - ), - DataToolUtils.bytesArrayListToBytes32ArrayList( - byteArray, - WeIdConstant.CPT_STRING_ARRAY_LENGTH - ), - DataToolUtils.stringToByte32ArrayList( - cptJsonSchemaNew, WeIdConstant.JSON_SCHEMA_ARRAY_LENGTH), - rsvSignature.getV().getValue(), - rsvSignature.getR().getValue(), - rsvSignature.getS().getValue() - ).send(); + if (dataStorageIndex == WeIdConstant.CPT_DATA_INDEX) { + transactionReceipt = cptController.updateCpt( + BigInteger.valueOf(Long.valueOf(cptId)), + address, + DataToolUtils.listToListBigInteger( + DataToolUtils.getParamCreatedList(WeIdConstant.CPT_LONG_ARRAY_LENGTH), + WeIdConstant.CPT_LONG_ARRAY_LENGTH + ), + DataToolUtils.bytesArrayListToBytes32ArrayList( + byteArray, + WeIdConstant.CPT_STRING_ARRAY_LENGTH + ), + DataToolUtils.stringToByte32ArrayList( + cptJsonSchemaNew, WeIdConstant.JSON_SCHEMA_ARRAY_LENGTH), + rsvSignature.getV().getValue(), + rsvSignature.getR().getValue(), + rsvSignature.getS().getValue() + ).send(); + } else { + transactionReceipt = cptController.updatePolicy( + BigInteger.valueOf(Long.valueOf(cptId)), + address, + DataToolUtils.listToListBigInteger( + DataToolUtils.getParamCreatedList(WeIdConstant.CPT_LONG_ARRAY_LENGTH), + WeIdConstant.CPT_LONG_ARRAY_LENGTH + ), + DataToolUtils.bytesArrayListToBytes32ArrayList( + byteArray, + WeIdConstant.CPT_STRING_ARRAY_LENGTH + ), + DataToolUtils.stringToByte32ArrayList( + cptJsonSchemaNew, WeIdConstant.JSON_SCHEMA_ARRAY_LENGTH), + rsvSignature.getV().getValue(), + rsvSignature.getR().getValue(), + rsvSignature.getS().getValue() + ).send(); + } ResponseData response = processUpdateEventLog(cptController, transactionReceipt); @@ -176,7 +201,7 @@ public ResponseData updateCpt(int cptId, String address, String cpt */ @Override public ResponseData registerCpt(int cptId, String address, String cptJsonSchemaNew, - RsvSignature rsvSignature, String privateKey) { + RsvSignature rsvSignature, String privateKey, int dataStorageIndex) { List byteArray = new ArrayList<>(); @@ -184,23 +209,43 @@ public ResponseData registerCpt(int cptId, String address, String c try { CptController cptController = reloadContract(fiscoConfig.getCptAddress(), privateKey, CptController.class); - transactionReceipt = cptController.registerCpt( - BigInteger.valueOf(cptId), - address, - DataToolUtils.listToListBigInteger( - DataToolUtils.getParamCreatedList(WeIdConstant.CPT_LONG_ARRAY_LENGTH), - WeIdConstant.CPT_LONG_ARRAY_LENGTH - ), - DataToolUtils.bytesArrayListToBytes32ArrayList( - byteArray, - WeIdConstant.CPT_STRING_ARRAY_LENGTH - ), - DataToolUtils.stringToByte32ArrayList( - cptJsonSchemaNew, WeIdConstant.JSON_SCHEMA_ARRAY_LENGTH), - rsvSignature.getV().getValue(), - rsvSignature.getR().getValue(), - rsvSignature.getS().getValue() - ).send(); + if (dataStorageIndex == WeIdConstant.CPT_DATA_INDEX) { + transactionReceipt = cptController.registerCpt( + BigInteger.valueOf(cptId), + address, + DataToolUtils.listToListBigInteger( + DataToolUtils.getParamCreatedList(WeIdConstant.CPT_LONG_ARRAY_LENGTH), + WeIdConstant.CPT_LONG_ARRAY_LENGTH + ), + DataToolUtils.bytesArrayListToBytes32ArrayList( + byteArray, + WeIdConstant.CPT_STRING_ARRAY_LENGTH + ), + DataToolUtils.stringToByte32ArrayList( + cptJsonSchemaNew, WeIdConstant.JSON_SCHEMA_ARRAY_LENGTH), + rsvSignature.getV().getValue(), + rsvSignature.getR().getValue(), + rsvSignature.getS().getValue() + ).send(); + } else { + transactionReceipt = cptController.registerPolicy( + BigInteger.valueOf(cptId), + address, + DataToolUtils.listToListBigInteger( + DataToolUtils.getParamCreatedList(WeIdConstant.CPT_LONG_ARRAY_LENGTH), + WeIdConstant.CPT_LONG_ARRAY_LENGTH + ), + DataToolUtils.bytesArrayListToBytes32ArrayList( + byteArray, + WeIdConstant.CPT_STRING_ARRAY_LENGTH + ), + DataToolUtils.stringToByte32ArrayList( + cptJsonSchemaNew, WeIdConstant.JSON_SCHEMA_ARRAY_LENGTH), + rsvSignature.getV().getValue(), + rsvSignature.getR().getValue(), + rsvSignature.getS().getValue() + ).send(); + } ResponseData response = processRegisterEventLog(cptController, transactionReceipt); @@ -230,31 +275,49 @@ public ResponseData registerCpt( String address, String cptJsonSchemaNew, RsvSignature rsvSignature, - String privateKey) { + String privateKey, + int dataStorageIndex) { List byteArray = new ArrayList<>(); TransactionReceipt transactionReceipt; try { CptController cptController = reloadContract(fiscoConfig.getCptAddress(), privateKey, CptController.class); - transactionReceipt = cptController.registerCpt( - address, - DataToolUtils.listToListBigInteger( - DataToolUtils.getParamCreatedList(WeIdConstant.CPT_LONG_ARRAY_LENGTH), - WeIdConstant.CPT_LONG_ARRAY_LENGTH - ), - DataToolUtils.bytesArrayListToBytes32ArrayList( - byteArray, - WeIdConstant.CPT_STRING_ARRAY_LENGTH - ), - DataToolUtils.stringToByte32ArrayList( - cptJsonSchemaNew, WeIdConstant.JSON_SCHEMA_ARRAY_LENGTH), - rsvSignature.getV().getValue(), - rsvSignature.getR().getValue(), - rsvSignature.getS().getValue() - ).send(); - - // + + if (dataStorageIndex == WeIdConstant.CPT_DATA_INDEX) { + transactionReceipt = cptController.registerCpt( + address, + DataToolUtils.listToListBigInteger( + DataToolUtils.getParamCreatedList(WeIdConstant.CPT_LONG_ARRAY_LENGTH), + WeIdConstant.CPT_LONG_ARRAY_LENGTH + ), + DataToolUtils.bytesArrayListToBytes32ArrayList( + byteArray, + WeIdConstant.CPT_STRING_ARRAY_LENGTH + ), + DataToolUtils.stringToByte32ArrayList( + cptJsonSchemaNew, WeIdConstant.JSON_SCHEMA_ARRAY_LENGTH), + rsvSignature.getV().getValue(), + rsvSignature.getR().getValue(), + rsvSignature.getS().getValue()).send(); + } else { + transactionReceipt = cptController.registerPolicy( + address, + DataToolUtils.listToListBigInteger( + DataToolUtils.getParamCreatedList(WeIdConstant.CPT_LONG_ARRAY_LENGTH), + WeIdConstant.CPT_LONG_ARRAY_LENGTH + ), + DataToolUtils.bytesArrayListToBytes32ArrayList( + byteArray, + WeIdConstant.CPT_STRING_ARRAY_LENGTH + ), + DataToolUtils.stringToByte32ArrayList( + cptJsonSchemaNew, WeIdConstant.JSON_SCHEMA_ARRAY_LENGTH), + rsvSignature.getV().getValue(), + rsvSignature.getR().getValue(), + rsvSignature.getS().getValue()).send(); + } + ResponseData response = processRegisterEventLog(cptController, transactionReceipt); if (response.getErrorCode().intValue() != ErrorCode.SUCCESS.getCode()) { @@ -365,14 +428,22 @@ private ResponseData processRegisterEventLog( * @see com.webank.weid.service.impl.engine.CptEngineController#queryCpt(int) */ @Override - public ResponseData queryCpt(int cptId) { + public ResponseData queryCpt(int cptId, int dataStorageIndex) { try { Tuple7, List, List, - BigInteger, byte[], byte[]> valueList = - cptController - .queryCpt(new BigInteger(String.valueOf(cptId))).sendAsync() + BigInteger, byte[], byte[]> valueList; + if (dataStorageIndex == WeIdConstant.CPT_DATA_INDEX) { + valueList = cptController + .queryCpt(new BigInteger(String.valueOf(cptId))) + .sendAsync() + .get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS); + } else { + valueList = cptController + .queryPolicy(new BigInteger(String.valueOf(cptId))) + .sendAsync() .get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS); + } if (valueList == null) { logger.error("Query cpt id : {} does not exist, result is null.", cptId); @@ -498,7 +569,7 @@ public ResponseData queryCredentialTemplate(Integer cp } } } - ResponseData resp = this.queryCpt(cptId); + ResponseData resp = this.queryCpt(cptId, WeIdConstant.CPT_DATA_INDEX); Cpt cpt = resp.getResult(); Map cptInfo = cpt.getCptJsonSchema(); @@ -519,4 +590,135 @@ public ResponseData queryCredentialTemplate(Integer cp return new ResponseData(credentialTemplateStorage, ErrorCode.SUCCESS); } + + @Override + public ResponseData putPolicyIntoPresentation(List policyIdList, + WeIdPrivateKey weIdPrivateKey) { + if (!WeIdUtils.isPrivateKeyValid(weIdPrivateKey) || !isPolicyIdListValid(policyIdList)) { + return new ResponseData<>(-1, ErrorCode.ILLEGAL_INPUT); + } + CptController cptController = + reloadContract(fiscoConfig.getCptAddress(), weIdPrivateKey.getPrivateKey(), + CptController.class); + List idBigIntList = new ArrayList<>(); + for (Integer policyId : policyIdList) { + idBigIntList.add(new BigInteger(String.valueOf(policyId), 10)); + } + try { + TransactionReceipt transactionReceipt = cptController + .putClaimPoliciesIntoPresentationMap(idBigIntList).send(); + ResponseData response = processRegisterEventLog(cptController, + transactionReceipt); + if (response.getErrorCode().intValue() == ErrorCode.SUCCESS.getCode()) { + return new ResponseData<>(response.getResult().getCptId().intValue(), + ErrorCode.SUCCESS); + } else { + return new ResponseData<>(-1, ErrorCode.UNKNOW_ERROR); + } + } catch (Exception e) { + logger.error("[register policy] register policy failed. exception message: ", e); + return new ResponseData(-1, ErrorCode.UNKNOW_ERROR); + } + } + + private boolean isPolicyIdListValid(List policyIdList) { + for (Integer policyId : policyIdList) { + if (policyId < 0) { + return false; + } + } + return true; + } + + @Override + public ResponseData getPolicyFromPresentation(Integer presentationId) { + try { + Tuple2, String> tuple = cptController + .getClaimPoliciesFromPresentationMap( + new BigInteger(String.valueOf(presentationId), 10)).send(); + List list = tuple.getValue1(); + List policies = new ArrayList<>(); + for (Object obj : list) { + policies.add(((BigInteger) obj).intValue()); + } + PresentationPolicyE presentationPolicy = new PresentationPolicyE(); + presentationPolicy.setId(presentationId); + Map policyMap = new HashMap<>(); + for (Integer id : policies) { + policyMap.put(id, null); + } + presentationPolicy.setPolicy(policyMap); + String addr = tuple.getValue2(); + presentationPolicy.setPolicyPublisherWeId(WeIdUtils.convertAddressToWeId(addr)); + return new ResponseData<>(presentationPolicy, ErrorCode.SUCCESS); + } catch (Exception e) { + logger.error("[queryCpt] query Cpt failed. exception message: ", e); + return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); + } + } + + @Override + public ResponseData putPolicyIntoCpt(Integer cptId, List policyIdList, + WeIdPrivateKey weIdPrivateKey) { + if (!WeIdUtils.isPrivateKeyValid(weIdPrivateKey) || !isPolicyIdListValid(policyIdList) + || cptId < 1) { + return new ResponseData<>(-1, ErrorCode.ILLEGAL_INPUT); + } + CptController cptController = + reloadContract(fiscoConfig.getCptAddress(), weIdPrivateKey.getPrivateKey(), + CptController.class); + List idBigIntList = new ArrayList<>(); + for (Integer policyId : policyIdList) { + idBigIntList.add(new BigInteger(String.valueOf(policyId), 10)); + } + try { + TransactionReceipt transactionReceipt = cptController + .putClaimPoliciesIntoCptMap(new BigInteger(String.valueOf(cptId), 10), idBigIntList) + .send(); + ResponseData response = processRegisterEventLog(cptController, + transactionReceipt); + if (response.getErrorCode().intValue() == ErrorCode.SUCCESS.getCode()) { + return new ResponseData<>(response.getResult().getCptId().intValue(), + ErrorCode.SUCCESS); + } else { + return new ResponseData<>(-1, ErrorCode.UNKNOW_ERROR); + } + } catch (Exception e) { + logger.error("[register policy] register policy failed. exception message: ", e); + return new ResponseData(-1, ErrorCode.UNKNOW_ERROR); + } + } + + @Override + public ResponseData> getPolicyFromCpt(Integer cptId) { + try { + List list = cptController.getClaimPoliciesFromCptMap( + new BigInteger(String.valueOf(cptId), 10)).send(); + List policies = new ArrayList<>(); + for (Object obj : list) { + policies.add(((BigInteger) obj).intValue()); + } + return new ResponseData<>(policies, ErrorCode.SUCCESS); + } catch (Exception e) { + logger.error("[queryCpt] query Cpt failed. exception message: ", e); + return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); + } + } + + @Override + public ResponseData> getCptLists(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 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); + return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR); + } + } } diff --git a/src/main/java/com/webank/weid/service/impl/engine/fiscov2/DataBucketServiceEngineV2.java b/src/main/java/com/webank/weid/service/impl/engine/fiscov2/DataBucketServiceEngineV2.java index f62311932..279b31648 100644 --- a/src/main/java/com/webank/weid/service/impl/engine/fiscov2/DataBucketServiceEngineV2.java +++ b/src/main/java/com/webank/weid/service/impl/engine/fiscov2/DataBucketServiceEngineV2.java @@ -5,7 +5,7 @@ import java.util.List; import org.apache.commons.lang3.StringUtils; -import org.bcos.web3j.abi.datatypes.generated.Bytes32; +import org.fisco.bcos.web3j.abi.datatypes.generated.Bytes32; import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; import org.fisco.bcos.web3j.tuples.generated.Tuple2; import org.fisco.bcos.web3j.tuples.generated.Tuple4; @@ -71,7 +71,7 @@ private DataBucket getDataBucket(String privateKey) { @Override public ResponseData put( - String hash, + String bucketId, String key, String value, WeIdPrivateKey privateKey) { @@ -79,18 +79,20 @@ public ResponseData put( Bytes32 keyByte32 = DataToolUtils.bytesArrayToBytes32(key.getBytes()); try { TransactionReceipt receipt = getDataBucket(privateKey.getPrivateKey()).put( - hash, keyByte32.getValue(), value).send(); + bucketId, keyByte32.getValue(), value).send(); if (StringUtils .equals(receipt.getStatus(), ParamKeyConstant.TRNSACTION_RECEIPT_STATUS_SUCCESS)) { - logger.info("[put] put [{}:{}] into chain success, hash is {}.", key, value, hash); + logger.info("[put] put [{}:{}] into chain success, bucketId is {}.", + key, value, bucketId); ErrorCode code = analysisErrorCode(receipt); return new ResponseData(code == ErrorCode.SUCCESS, code); } - logger.error("[put] put [{}:{}] into chain fail, hash is {}.", key, value, hash); + logger.error("[put] put [{}:{}] into chain fail, bucketId is {}.", + key, value, bucketId); return new ResponseData(false, ErrorCode.TRANSACTION_EXECUTE_ERROR); } catch (Exception e) { - logger.error("[put] put [{}:{}] into chain has excpetion, hash is {}, exception:", - key, value, hash, e); + logger.error("[put] put [{}:{}] into chain has excpetion, bucketId is {}, exception:", + key, value, bucketId, e); return new ResponseData(false, ErrorCode.UNKNOW_ERROR); } } @@ -133,28 +135,30 @@ private ErrorCode analysisErrorCode(TransactionReceipt receipt) { } @Override - public ResponseData get(String hash, String key) { + public ResponseData get(String bucketId, String key) { Bytes32 keyByte32 = DataToolUtils.bytesArrayToBytes32(key.getBytes()); try { - Tuple2 tuple = dataBucket.get(hash, keyByte32.getValue()).send(); + Tuple2 tuple = dataBucket.get( + bucketId, keyByte32.getValue()).send(); int code = tuple.getValue1().intValue(); if (code == 102) { - logger.error("[get] the hash does not exits, hash is {}.", hash); + logger.error("[get] the bucketId does not exits, bucketId is {}.", bucketId); return new ResponseData(StringUtils.EMPTY, ErrorCode.CNS_DOES_NOT_EXIST); } - logger.info("[get] get address successfully, hash: {}, key: {}, value: {}", - hash, key, tuple.getValue2()); + logger.info("[get] get address successfully, bucketId: {}, key: {}, value: {}", + bucketId, key, tuple.getValue2()); return new ResponseData(tuple.getValue2(), ErrorCode.SUCCESS); } catch (Exception e) { logger.error( - "[get] get data has exception, hash is {}, key is {}, exception:", hash, key, e); + "[get] get data has exception, bucketId is {}, key is {}, exception:", + bucketId, key, e); return new ResponseData(StringUtils.EMPTY, ErrorCode.UNKNOW_ERROR); } } @Override public ResponseData removeExtraItem( - String hash, + String bucketId, String key, WeIdPrivateKey privateKey ) { @@ -165,46 +169,49 @@ public ResponseData removeExtraItem( keyByte32 = DataToolUtils.bytesArrayToBytes32(key.getBytes()); } try { - logger.info("[remove] remove Extra Item, hash is {}, key is {}.", hash, key); + logger.info("[remove] remove Extra Item, bucketId is {}, key is {}.", bucketId, key); TransactionReceipt receipt = getDataBucket(privateKey.getPrivateKey()).removeExtraItem( - hash, keyByte32.getValue()).send(); + bucketId, keyByte32.getValue()).send(); if (StringUtils .equals(receipt.getStatus(), ParamKeyConstant.TRNSACTION_RECEIPT_STATUS_SUCCESS)) { - logger.info("[remove] remove {} from chain success, hash is {}.", key, hash); + logger.info("[remove] remove {} from chain success, bucketId is {}.", + key, bucketId); ErrorCode code = analysisErrorCode(receipt); return new ResponseData(code == ErrorCode.SUCCESS, code); } - logger.error("[remove] remove {} from chain fail, hash is {}.", key, hash); + logger.error("[remove] remove {} from chain fail, bucketId is {}.", key, bucketId); return new ResponseData(false, ErrorCode.TRANSACTION_EXECUTE_ERROR); } catch (Exception e) { - logger.error("[remove] remove {} from chain has excpetion, hash is {}, exception:", - key, hash, e); + logger.error("[remove] remove {} from chain has excpetion, bucketId is {}, exception:", + key, bucketId, e); return new ResponseData(false, ErrorCode.UNKNOW_ERROR); } } @Override public ResponseData removeDataBucketItem( - String hash, + String bucketId, boolean force, WeIdPrivateKey privateKey ) { try { - logger.info("[remove] remove Bucket Item, hash is {}, force is {}.", hash, force); + logger.info("[remove] remove Bucket Item, bucketId is {}, force is {}.", + bucketId, force); TransactionReceipt receipt = getDataBucket(privateKey.getPrivateKey()) - .removeDataBucketItem(hash, force).send(); + .removeDataBucketItem(bucketId, force).send(); if (StringUtils .equals(receipt.getStatus(), ParamKeyConstant.TRNSACTION_RECEIPT_STATUS_SUCCESS)) { - logger.info("[remove] remove Bucket Item from chain success, hash is {}.", hash); + logger.info("[remove] remove Bucket Item from chain success, bucketId is {}.", + bucketId); ErrorCode code = analysisErrorCode(receipt); return new ResponseData(code == ErrorCode.SUCCESS, code); } - logger.error("[remove] remove Bucket Item from chain fail, hash is {}.", hash); + logger.error("[remove] remove Bucket Item from chain fail, bucketId is {}.", bucketId); return new ResponseData(false, ErrorCode.TRANSACTION_EXECUTE_ERROR); } catch (Exception e) { logger.error( - "[remove] remove Bucket Item from chain has excpetion, hash is {}, exception:", - hash, + "[remove] remove Bucket Item from chain has excpetion, bucketId is {}, exception:", + bucketId, e ); return new ResponseData(false, ErrorCode.UNKNOW_ERROR); @@ -212,46 +219,47 @@ public ResponseData removeDataBucketItem( } @Override - public ResponseData enableHash(String hash, WeIdPrivateKey privateKey) { + public ResponseData enable(String bucketId, WeIdPrivateKey privateKey) { try { - TransactionReceipt receipt = getDataBucket(privateKey.getPrivateKey()).enableHash( - hash).send(); + TransactionReceipt receipt = getDataBucket(privateKey.getPrivateKey()).enable( + bucketId).send(); if (StringUtils .equals(receipt.getStatus(), ParamKeyConstant.TRNSACTION_RECEIPT_STATUS_SUCCESS)) { - logger.info("[enableHash] enable hash success, hash is {}.", hash); + logger.info("[enable] enable Bucket success, bucketId is {}.", bucketId); ErrorCode code = analysisErrorCode(receipt); return new ResponseData(code == ErrorCode.SUCCESS, code); } - logger.error("[enableHash] enable hash fail, hash is {}.", hash); + logger.error("[enable] enable Bucket fail, bucketId is {}.", bucketId); return new ResponseData(false, ErrorCode.TRANSACTION_EXECUTE_ERROR); } catch (Exception e) { - logger.error("[enableHash] enable hash has excpetion, hash is {}, exception:", hash, e); + logger.error("[enable] enable Bucket has excpetion, bucketId is {}, exception:", + bucketId, e); return new ResponseData(false, ErrorCode.UNKNOW_ERROR); } } @Override - public ResponseData disableHash(String hash, WeIdPrivateKey privateKey) { + public ResponseData disable(String bucketId, WeIdPrivateKey privateKey) { try { - TransactionReceipt receipt = getDataBucket(privateKey.getPrivateKey()).disableHash( - hash).send(); + TransactionReceipt receipt = getDataBucket(privateKey.getPrivateKey()).disable( + bucketId).send(); if (StringUtils .equals(receipt.getStatus(), ParamKeyConstant.TRNSACTION_RECEIPT_STATUS_SUCCESS)) { - logger.info("[disableHash] disable hash success, hash is {}.", hash); + logger.info("[disable] disable Bucket success, bucketId is {}.", bucketId); ErrorCode code = analysisErrorCode(receipt); return new ResponseData(code == ErrorCode.SUCCESS, code); } - logger.error("[disableHash] disable hash fail, hash is {}.", hash); + logger.error("[disable] disable Bucket fail, bucketId is {}.", bucketId); return new ResponseData(false, ErrorCode.TRANSACTION_EXECUTE_ERROR); } catch (Exception e) { - logger.error("[disableHash] disable hash has excpetion, hash is {}, exception:", - hash, e); + logger.error("[disable] disable Bucket has excpetion, bucketId is {}, exception:", + bucketId, e); return new ResponseData(false, ErrorCode.UNKNOW_ERROR); } } @Override - public ResponseData> getAllHash() { + public ResponseData> getAllBucket() { int startIndex = 0; BigInteger num = BigInteger.valueOf(10); List hashContractList = new ArrayList(); @@ -259,17 +267,17 @@ public ResponseData> getAllHash() { while (true) { BigInteger offset = BigInteger.valueOf(startIndex); Tuple4, List, List, BigInteger> data = - dataBucket.getAllHash(offset, num).send(); - List hashList = data.getValue1(); + dataBucket.getAllBucket(offset, num).send(); + List bucketIdList = data.getValue1(); List ownerList = data.getValue2(); List timesList = data.getValue3(); BigInteger next = data.getValue4(); - for (int i = 0; i < hashList.size(); i++) { + for (int i = 0; i < bucketIdList.size(); i++) { if (WeIdUtils.isEmptyStringAddress(ownerList.get(i))) { break; } HashContract hash = new HashContract(); - hash.setHash(hashList.get(i)); + hash.setHash(bucketIdList.get(i)); hash.setOwner(ownerList.get(i)); hash.setTime(timesList.get(i).longValue()); hashContractList.add(hash); @@ -279,35 +287,67 @@ public ResponseData> getAllHash() { } startIndex = next.intValue(); } - logger.info("[getAllHash] get the all hash success."); + logger.info("[getAllBucket] get the all Bucket success."); return new ResponseData>(hashContractList, ErrorCode.SUCCESS); } catch (Exception e) { - logger.error("[getAllHash] get the all hash fail.", e); + logger.error("[getAllBucket] get the all Bucket fail.", e); return new ResponseData>(hashContractList, ErrorCode.UNKNOW_ERROR); } } @Override - public ResponseData updateHashOwner( - String hash, + public ResponseData updateBucketOwner( + String bucketId, String newOwner, WeIdPrivateKey privateKey ) { try { - TransactionReceipt receipt = getDataBucket(privateKey.getPrivateKey()).updateHashOwner( - hash, newOwner).send(); + TransactionReceipt receipt = getDataBucket(privateKey.getPrivateKey()) + .updateBucketOwner(bucketId, newOwner).send(); if (StringUtils .equals(receipt.getStatus(), ParamKeyConstant.TRNSACTION_RECEIPT_STATUS_SUCCESS)) { - logger.info("[updateHashOwner] update owner success, hash is {}.", hash); + logger.info("[updateBucketOwner] update owner success, bucketId is {}.", bucketId); ErrorCode code = analysisErrorCode(receipt); return new ResponseData(code == ErrorCode.SUCCESS, code); } - logger.error("[updateHashOwner] update owner fail, hash is {}.", hash); + logger.error("[updateBucketOwner] update owner fail, bucketId is {}.", bucketId); return new ResponseData(false, ErrorCode.TRANSACTION_EXECUTE_ERROR); } catch (Exception e) { - logger.error("[updateHashOwner] update owner has excpetion, hash is {}, exception:", - hash, e); + logger.error( + "[updateBucketOwner] update owner has excpetion, bucketId is {}, exception:", + bucketId, e); return new ResponseData(false, ErrorCode.UNKNOW_ERROR); } } + + @Override + public ResponseData> getActivatedUserList(String bucketId) { + int startIndex = 0; + BigInteger num = BigInteger.valueOf(10); + List userList = new ArrayList(); + try { + while (true) { + BigInteger index = BigInteger.valueOf(startIndex); + Tuple2, BigInteger> data = + dataBucket.getActivatedUserList(bucketId, index, num).send(); + List useList = data.getValue1(); + BigInteger next = data.getValue2(); + for (int i = 0; i < useList.size(); i++) { + if (WeIdUtils.isEmptyStringAddress(useList.get(i))) { + break; + } + userList.add(useList.get(i)); + } + if (next.intValue() == 0) { + break; + } + startIndex = next.intValue(); + } + logger.info("[getActivatedUserList] get the use list by bucketId success."); + return new ResponseData>(userList, ErrorCode.SUCCESS); + } catch (Exception e) { + logger.error("[getActivatedUserList] get the use list by bucketId fail.", e); + return new ResponseData>(userList, ErrorCode.UNKNOW_ERROR); + } + } } diff --git a/src/main/java/com/webank/weid/service/impl/engine/fiscov2/EvidenceServiceEngineV2.java b/src/main/java/com/webank/weid/service/impl/engine/fiscov2/EvidenceServiceEngineV2.java index 230321532..7cd10a0e8 100644 --- a/src/main/java/com/webank/weid/service/impl/engine/fiscov2/EvidenceServiceEngineV2.java +++ b/src/main/java/com/webank/weid/service/impl/engine/fiscov2/EvidenceServiceEngineV2.java @@ -19,12 +19,13 @@ package com.webank.weid.service.impl.engine.fiscov2; -import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; +import java.util.HashMap; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; @@ -45,6 +46,7 @@ import com.webank.weid.constant.WeIdConstant; import com.webank.weid.contract.v2.EvidenceContract; import com.webank.weid.contract.v2.EvidenceContract.EvidenceAttributeChangedEventResponse; +import com.webank.weid.contract.v2.EvidenceContract.EvidenceExtraAttributeChangedEventResponse; import com.webank.weid.exception.WeIdBaseException; import com.webank.weid.protocol.base.EvidenceInfo; import com.webank.weid.protocol.base.EvidenceSignInfo; @@ -53,7 +55,6 @@ import com.webank.weid.protocol.response.TransactionInfo; import com.webank.weid.service.impl.engine.BaseEngine; import com.webank.weid.service.impl.engine.EvidenceServiceEngine; -import com.webank.weid.service.impl.inner.PropertiesService; import com.webank.weid.suite.cache.CacheManager; import com.webank.weid.suite.cache.CacheNode; import com.webank.weid.util.DataToolUtils; @@ -98,7 +99,8 @@ private void initEvidenceAddress() { this.evidenceAddress = super.getBucket(CnsType.ORG_CONFING).get( fiscoConfig.getCurrentOrgId(), WeIdConstant.CNS_EVIDENCE_ADDRESS + groupId).getResult(); if (StringUtils.isBlank(evidenceAddress)) { - throw new WeIdBaseException("can not found the evidence address from chain"); + throw new WeIdBaseException("can not found the evidence address from chain, you may " + + "not activate the evidence contract on WeID Build Tools."); } logger.info( "[initEvidenceAddress] get the address from cns. address = {}", @@ -148,9 +150,12 @@ public ResponseData createEvidence( TransactionInfo info = new TransactionInfo(receipt); List eventList = evidenceContract.getEvidenceAttributeChangedEvents(receipt); - if (eventList == null || eventList.isEmpty()) { + if (eventList == null) { return new ResponseData<>(StringUtils.EMPTY, ErrorCode.CREDENTIAL_EVIDENCE_BASE_ERROR, info); + } else if (eventList.isEmpty()) { + return new ResponseData<>(StringUtils.EMPTY, + ErrorCode.CREDENTIAL_EVIDENCE_ALREADY_EXISTS, info); } else { for (EvidenceAttributeChangedEventResponse event : eventList) { if (event.sigs.toArray()[0].toString().equalsIgnoreCase(signature) @@ -218,9 +223,11 @@ public ResponseData> batchCreateEvidence( TransactionInfo info = new TransactionInfo(receipt); List eventList = evidenceContractWriter.getEvidenceAttributeChangedEvents(receipt); - if (eventList == null || eventList.isEmpty()) { - return new ResponseData<>(result, - ErrorCode.CREDENTIAL_EVIDENCE_BASE_ERROR, info); + if (eventList == null) { + return new ResponseData<>(result, ErrorCode.CREDENTIAL_EVIDENCE_BASE_ERROR, info); + } else if (eventList.isEmpty()) { + return new ResponseData<>(result, ErrorCode.CREDENTIAL_EVIDENCE_ALREADY_EXISTS, + info); } else { List returnedHashs = new ArrayList<>(); for (EvidenceAttributeChangedEventResponse event : eventList) { @@ -296,9 +303,12 @@ public ResponseData> batchCreateEvidenceWithCustomKey( TransactionInfo info = new TransactionInfo(receipt); List eventList = evidenceContractWriter.getEvidenceAttributeChangedEvents(receipt); - if (eventList == null || eventList.isEmpty()) { + if (eventList == null) { return new ResponseData<>(result, ErrorCode.CREDENTIAL_EVIDENCE_BASE_ERROR, info); + } else if (eventList.isEmpty()) { + return new ResponseData<>(result, ErrorCode.CREDENTIAL_EVIDENCE_ALREADY_EXISTS, + info); } else { List returnedHashs = new ArrayList<>(); for (EvidenceAttributeChangedEventResponse event : eventList) { @@ -322,6 +332,7 @@ public ResponseData> batchCreateEvidenceWithCustomKey( @Override public ResponseData addLog( String hashValue, + String sig, String log, Long timestamp, String privateKey @@ -333,7 +344,7 @@ public ResponseData addLog( } hashByteList.add(DataToolUtils.convertHashStrIntoHashByte32Array(hashValue)); List sigList = new ArrayList<>(); - sigList.add(StringUtils.EMPTY); + sigList.add(sig); List logList = new ArrayList<>(); logList.add(log); List timestampList = new ArrayList<>(); @@ -348,9 +359,8 @@ public ResponseData addLog( privateKey, EvidenceContract.class ); - signerList.add(address); TransactionReceipt receipt = - evidenceContractWriter.createEvidence( + evidenceContractWriter.addSignatureAndLogs( hashByteList, signerList, sigList, @@ -360,8 +370,75 @@ public ResponseData addLog( TransactionInfo info = new TransactionInfo(receipt); List eventList = evidenceContractWriter.getEvidenceAttributeChangedEvents(receipt); - if (eventList == null || eventList.isEmpty()) { + if (eventList == null) { + return new ResponseData<>(false, ErrorCode.CREDENTIAL_EVIDENCE_BASE_ERROR, info); + } else if (eventList.isEmpty()) { + return new ResponseData<>(false, ErrorCode.CREDENTIAL_EVIDENCE_NOT_EXIST, info); + } else { + for (EvidenceAttributeChangedEventResponse event : eventList) { + if (event.signer.toArray()[0].toString().equalsIgnoreCase(address)) { + return new ResponseData<>(true, ErrorCode.SUCCESS, info); + } + } + } + return new ResponseData<>(false, + ErrorCode.CREDENTIAL_EVIDENCE_CONTRACT_FAILURE_ILLEAGAL_INPUT); + } catch (Exception e) { + logger.error("add log failed due to system error. ", e); + return new ResponseData<>(false, ErrorCode.CREDENTIAL_EVIDENCE_BASE_ERROR); + } + } + + @Override + public ResponseData addLogByCustomKey( + String hashValue, + String sig, + String log, + Long timestamp, + String customKey, + String privateKey + ) { + try { + List hashByteList = new ArrayList<>(); + if (!DataToolUtils.isValidHash(hashValue)) { + return new ResponseData<>(false, ErrorCode.ILLEGAL_INPUT, null); + } + hashByteList.add(DataToolUtils.convertHashStrIntoHashByte32Array(hashValue)); + List sigList = new ArrayList<>(); + sigList.add(sig); + List logList = new ArrayList<>(); + logList.add(log); + List timestampList = new ArrayList<>(); + timestampList.add(new BigInteger(String.valueOf(timestamp), 10)); + String address = WeIdUtils + .convertWeIdToAddress(DataToolUtils.convertPrivateKeyToDefaultWeId(privateKey)); + List signerList = new ArrayList<>(); + signerList.add(address); + List customKeyList = new ArrayList<>(); + customKeyList.add(customKey); + EvidenceContract evidenceContractWriter = + reloadContract( + this.evidenceAddress, + privateKey, + EvidenceContract.class + ); + signerList.add(address); + TransactionReceipt receipt = + evidenceContractWriter.addSignatureAndLogsWithExtraKey( + hashByteList, + signerList, + sigList, + logList, + timestampList, + customKeyList + ).send(); + TransactionInfo info = new TransactionInfo(receipt); + List eventList = + evidenceContractWriter.getEvidenceAttributeChangedEvents(receipt); + if (eventList == null) { return new ResponseData<>(false, ErrorCode.CREDENTIAL_EVIDENCE_BASE_ERROR, info); + } else if (eventList.isEmpty()) { + return new ResponseData<>(false, ErrorCode.CREDENTIAL_EVIDENCE_NOT_EXIST, info); } else { for (EvidenceAttributeChangedEventResponse event : eventList) { if (event.signer.toArray()[0].toString().equalsIgnoreCase(address)) { @@ -401,6 +478,7 @@ public ResponseData getHashByCustomKey(String customKey) { public ResponseData getInfo(String hash) { EvidenceInfo evidenceInfo = new EvidenceInfo(); evidenceInfo.setCredentialHash(hash); + Map> perSignerRedoLog = new HashMap<>(); int latestBlockNumber = 0; byte[] hashByte = DataToolUtils.convertHashStrIntoHashByte32Array(hash); try { @@ -409,7 +487,7 @@ public ResponseData getInfo(String hash) { if (latestBlockNumber == 0) { return new ResponseData<>(null, ErrorCode.CREDENTIAL_EVIDENCE_NOT_EXIST); } - resolveTransaction(hash, latestBlockNumber, evidenceInfo); + resolveTransaction(hash, latestBlockNumber, evidenceInfo, perSignerRedoLog); // Reverse the order of the list for (String signer : evidenceInfo.getSigners()) { List extraList = evidenceInfo.getSignInfo().get(signer).getLogs(); @@ -427,7 +505,8 @@ public ResponseData getInfo(String hash) { private void resolveTransaction( String hash, int startBlockNumber, - EvidenceInfo evidenceInfo) { + EvidenceInfo evidenceInfo, + Map> perSignerRedoLog) { int previousBlock = startBlockNumber; while (previousBlock != 0) { @@ -469,7 +548,7 @@ private void resolveTransaction( topicSet.add(log.getTopics().get(0)); } ResolveEventLogResult returnValue = - resolveEventLog(hash, log, receipt, evidenceInfo); + resolveEventLog(hash, log, receipt, evidenceInfo, perSignerRedoLog); if (returnValue.getResultStatus().equals( ResolveEventLogStatus.STATUS_SUCCESS)) { if (returnValue.getPreviousBlock() == currentBlockNumber) { @@ -489,10 +568,11 @@ private ResolveEventLogResult resolveEventLog( String hash, Log log, TransactionReceipt receipt, - EvidenceInfo evidenceInfo) { + EvidenceInfo evidenceInfo, + Map> perSignerRedoLog) { String topic = log.getTopics().get(0); if (!StringUtils.isBlank(topic)) { - return resolveAttributeEvent(hash, receipt, evidenceInfo); + return resolveAttributeEvent(hash, receipt, evidenceInfo, perSignerRedoLog); } ResolveEventLogResult response = new ResolveEventLogResult(); response.setResolveEventLogStatus(ResolveEventLogStatus.STATUS_EVENT_NULL); @@ -502,99 +582,185 @@ private ResolveEventLogResult resolveEventLog( private ResolveEventLogResult resolveAttributeEvent( String hash, TransactionReceipt receipt, - EvidenceInfo evidenceInfo) { + EvidenceInfo evidenceInfo, + Map> perSignerRedoLog) { List eventList = evidenceContract.getEvidenceAttributeChangedEvents(receipt); + List extraEventList = + evidenceContract.getEvidenceExtraAttributeChangedEvents(receipt); ResolveEventLogResult response = new ResolveEventLogResult(); - if (CollectionUtils.isEmpty(eventList)) { + if (CollectionUtils.isEmpty(eventList) && CollectionUtils.isEmpty(extraEventList)) { response.setResolveEventLogStatus(ResolveEventLogStatus.STATUS_EVENTLOG_NULL); return response; } int previousBlock = 0; - // Actual construction code - // there should be only 1 attrib-change event so it is fine to do so - for (EvidenceAttributeChangedEventResponse event : eventList) { - if (CollectionUtils.isEmpty(event.signer) || CollectionUtils.isEmpty(event.hash)) { - response.setResolveEventLogStatus(ResolveEventLogStatus.STATUS_RES_NULL); - return response; - } - // the event is a full list of everything. Go thru the list and locate the hash - for (int index = 0; index < CollectionUtils.size(event.hash); index++) { - if (hash.equalsIgnoreCase(DataToolUtils.convertHashByte32ArrayIntoHashStr( - ((Bytes32) event.hash.toArray()[index]).getValue()))) { - String signerWeId = WeIdUtils - .convertAddressToWeId(event.signer.toArray()[index].toString()); - String currentLog = event.logs.toArray()[index].toString(); - String currentSig = event.sigs.toArray()[index].toString(); - if (!StringUtils.isEmpty(currentLog) && !StringUtils.isEmpty(currentSig)) { - // this is a sign/log event, sig will override unconditionally, - // but logs will try to append. - EvidenceSignInfo signInfo = new EvidenceSignInfo(); - signInfo.setSignature(currentSig); - if (evidenceInfo.getSignInfo().containsKey(signerWeId)) { - signInfo.setTimestamp( - evidenceInfo.getSignInfo().get(signerWeId).getTimestamp()); - List oldLogs = evidenceInfo.getSignInfo().get(signerWeId) - .getLogs(); - oldLogs.add(currentLog); - signInfo.setLogs(oldLogs); - } else { - signInfo - .setTimestamp(String.valueOf( - ((Uint256) event.updated.toArray()[index]).getValue() - .longValue())); - signInfo.getLogs().add(currentLog); + if (!CollectionUtils.isEmpty(eventList)) { + // Actual construction code + // there should be only 1 attrib-change event so it is fine to do so + for (EvidenceAttributeChangedEventResponse event : eventList) { + if (CollectionUtils.isEmpty(event.signer) || CollectionUtils.isEmpty(event.hash)) { + response.setResolveEventLogStatus(ResolveEventLogStatus.STATUS_RES_NULL); + return response; + } + // the event is a full list of everything. Go thru the list and locate the hash + for (int index = 0; index < CollectionUtils.size(event.hash); index++) { + if (hash.equalsIgnoreCase(DataToolUtils.convertHashByte32ArrayIntoHashStr( + ((Bytes32) event.hash.toArray()[index]).getValue()))) { + String signerWeId = WeIdUtils + .convertAddressToWeId(event.signer.toArray()[index].toString()); + if (CollectionUtils.size(perSignerRedoLog.get(signerWeId)) == 0) { + perSignerRedoLog.put(signerWeId, new ArrayList<>()); } - evidenceInfo.getSignInfo().put(signerWeId, signInfo); - } else if (!StringUtils.isEmpty(currentLog)) { - // this is a pure log event, just keep appending - EvidenceSignInfo tempInfo = new EvidenceSignInfo(); - if (evidenceInfo.getSignInfo().containsKey(signerWeId)) { - // already existing evidenceInfo, hence just append a log entry. - // sig will override, timestamp will use existing one (always newer) - tempInfo.setSignature( - evidenceInfo.getSignInfo().get(signerWeId).getSignature()); - tempInfo.setTimestamp( - evidenceInfo.getSignInfo().get(signerWeId).getTimestamp()); - List oldLogs = evidenceInfo.getSignInfo().get(signerWeId) - .getLogs(); - oldLogs.add(currentLog); - tempInfo.setLogs(oldLogs); + String currentLog = event.logs.toArray()[index].toString(); + String currentSig = event.sigs.toArray()[index].toString(); + if (!StringUtils.isEmpty(currentLog) && !StringUtils.isEmpty(currentSig)) { + // this is a sign/log event, sig will override unconditionally, + // but logs will try to append. + EvidenceSignInfo signInfo = new EvidenceSignInfo(); + signInfo.setSignature(currentSig); + if (evidenceInfo.getSignInfo().containsKey(signerWeId)) { + signInfo.setTimestamp( + evidenceInfo.getSignInfo().get(signerWeId).getTimestamp()); + List oldLogs = evidenceInfo.getSignInfo().get(signerWeId) + .getLogs(); + perSignerRedoLog.get(signerWeId).add(currentLog); + oldLogs.addAll(perSignerRedoLog.get(signerWeId)); + perSignerRedoLog.put(signerWeId, new ArrayList<>()); + signInfo.setLogs(oldLogs); + signInfo.setRevoked( + evidenceInfo.getSignInfo().get(signerWeId).getRevoked()); + } else { + signInfo + .setTimestamp(String.valueOf( + ((Uint256) event.updated.toArray()[index]).getValue() + .longValue())); + perSignerRedoLog.get(signerWeId).add(currentLog); + signInfo.getLogs().addAll(perSignerRedoLog.get(signerWeId)); + perSignerRedoLog.put(signerWeId, new ArrayList<>()); + } + evidenceInfo.getSignInfo().put(signerWeId, signInfo); + } else if (!StringUtils.isEmpty(currentLog)) { + // this is a pure log event, just keep appending + EvidenceSignInfo tempInfo = new EvidenceSignInfo(); + if (evidenceInfo.getSignInfo().containsKey(signerWeId)) { + // already existing evidenceInfo, hence just append a log entry. + // sig will override, timestamp will use existing one (always newer) + tempInfo.setSignature( + evidenceInfo.getSignInfo().get(signerWeId).getSignature()); + tempInfo.setTimestamp( + evidenceInfo.getSignInfo().get(signerWeId).getTimestamp()); + List oldLogs = evidenceInfo.getSignInfo().get(signerWeId) + .getLogs(); + //oldLogs.add(currentLog); + tempInfo.setLogs(oldLogs); + tempInfo.setRevoked( + evidenceInfo.getSignInfo().get(signerWeId).getRevoked()); + perSignerRedoLog.get(signerWeId).add(currentLog); + } else { + // haven't constructed anything yet, so create a new one now + tempInfo.setSignature(StringUtils.EMPTY); + tempInfo + .setTimestamp(String.valueOf( + ((Uint256) event.updated.toArray()[index]).getValue() + .longValue())); + //tempInfo.getLogs().add(currentLog); + perSignerRedoLog.get(signerWeId).add(currentLog); + } + evidenceInfo.getSignInfo().put(signerWeId, tempInfo); + } else if (!StringUtils.isEmpty(currentSig)) { + // this is a pure sig event, just override + EvidenceSignInfo signInfo = new EvidenceSignInfo(); + signInfo.setSignature(currentSig); + if (evidenceInfo.getSignInfo().containsKey(signerWeId)) { + signInfo.setTimestamp( + evidenceInfo.getSignInfo().get(signerWeId).getTimestamp()); + evidenceInfo.getSignInfo().get(signerWeId).getLogs() + .addAll(perSignerRedoLog.get(signerWeId)); + signInfo + .setLogs(evidenceInfo.getSignInfo().get(signerWeId).getLogs()); + perSignerRedoLog.put(signerWeId, new ArrayList<>()); + signInfo.setRevoked( + evidenceInfo.getSignInfo().get(signerWeId).getRevoked()); + } else { + signInfo + .setTimestamp(String.valueOf( + ((Uint256) event.updated.toArray()[index]).getValue() + .longValue())); + signInfo.setLogs(perSignerRedoLog.get(signerWeId)); + perSignerRedoLog.put(signerWeId, new ArrayList<>()); + } + evidenceInfo.getSignInfo().put(signerWeId, signInfo); } else { - // haven't constructed anything yet, so create a new one now - tempInfo.setSignature(StringUtils.EMPTY); - tempInfo - .setTimestamp(String.valueOf( - ((Uint256) event.updated.toArray()[index]).getValue() - .longValue())); - tempInfo.getLogs().add(currentLog); + // An empty event + continue; } - evidenceInfo.getSignInfo().put(signerWeId, tempInfo); - } else if (!StringUtils.isEmpty(currentSig)) { - // this is a pure sig event, just override - EvidenceSignInfo signInfo = new EvidenceSignInfo(); - signInfo.setSignature(currentSig); - if (evidenceInfo.getSignInfo().containsKey(signerWeId)) { - signInfo.setTimestamp( - evidenceInfo.getSignInfo().get(signerWeId).getTimestamp()); - signInfo.setLogs(evidenceInfo.getSignInfo().get(signerWeId).getLogs()); + previousBlock = ((Uint256) event.previousBlock.toArray()[index]).getValue() + .intValue(); + } + } + } + } + if (!CollectionUtils.isEmpty(extraEventList)) { + for (EvidenceExtraAttributeChangedEventResponse event : extraEventList) { + if (CollectionUtils.isEmpty(event.signer) || CollectionUtils.isEmpty(event.hash)) { + response.setResolveEventLogStatus(ResolveEventLogStatus.STATUS_RES_NULL); + return response; + } + for (int index = 0; index < CollectionUtils.size(event.hash); index++) { + if (hash.equalsIgnoreCase(DataToolUtils.convertHashByte32ArrayIntoHashStr( + ((Bytes32) event.hash.toArray()[index]).getValue()))) { + String signerWeId = WeIdUtils + .convertAddressToWeId(event.signer.toArray()[index].toString()); + String attributeKey = event.keys.toArray()[index].toString(); + if (attributeKey.equalsIgnoreCase(WeIdConstant.EVIDENCE_REVOKE_KEY)) { + // this is a revoke event. Use the first to be found unconditionally. + if (evidenceInfo.getSignInfo().containsKey(signerWeId)) { + // already existing evidence info, just modify status + if (evidenceInfo.getSignInfo().get(signerWeId).getRevoked() + == null) { + evidenceInfo.getSignInfo().get(signerWeId).setRevoked(true); + } + } else { + // Non existent evidence info, create a new one with time & stat + EvidenceSignInfo signInfo = new EvidenceSignInfo(); + signInfo.setTimestamp( + String.valueOf(((Uint256) event.updated.toArray()[index]) + .getValue().longValue())); + signInfo.setRevoked(true); + evidenceInfo.getSignInfo().put(signerWeId, signInfo); + } + } else if (attributeKey + .equalsIgnoreCase(WeIdConstant.EVIDENCE_UNREVOKE_KEY)) { + if (evidenceInfo.getSignInfo().containsKey(signerWeId)) { + // already existing evidence info, just modify timestamp & status + evidenceInfo.getSignInfo().get(signerWeId).setTimestamp( + String.valueOf(((Uint256) event.updated.toArray()[index]) + .getValue().longValue())); + if (evidenceInfo.getSignInfo().get(signerWeId).getRevoked() + == null) { + evidenceInfo.getSignInfo().get(signerWeId).setRevoked(false); + } + } else { + // Non existent evidence info, create a new one with time & stat + EvidenceSignInfo signInfo = new EvidenceSignInfo(); + signInfo.setTimestamp( + String.valueOf(((Uint256) event.updated.toArray()[index]) + .getValue().longValue())); + signInfo.setRevoked(false); + evidenceInfo.getSignInfo().put(signerWeId, signInfo); + } } else { - signInfo - .setTimestamp(String.valueOf( - ((Uint256) event.updated.toArray()[index]).getValue() - .longValue())); + // other keys attribute, please add in here + continue; } - evidenceInfo.getSignInfo().put(signerWeId, signInfo); - } else { - // An empty event - continue; + previousBlock = ((Uint256) event.previousBlock.toArray()[index]).getValue() + .intValue(); } - previousBlock = ((Uint256) event.previousBlock.toArray()[index]).getValue() - .intValue(); } } } + response.setPreviousBlock(previousBlock); response.setResolveEventLogStatus(ResolveEventLogStatus.STATUS_SUCCESS); return response; @@ -650,9 +816,12 @@ public ResponseData createEvidenceWithCustomKey( TransactionInfo info = new TransactionInfo(receipt); List eventList = evidenceContractWriter.getEvidenceAttributeChangedEvents(receipt); - if (eventList == null || eventList.isEmpty()) { + if (eventList == null) { return new ResponseData<>(StringUtils.EMPTY, ErrorCode.CREDENTIAL_EVIDENCE_BASE_ERROR, info); + } else if (eventList.isEmpty()) { + return new ResponseData<>(StringUtils.EMPTY, + ErrorCode.CREDENTIAL_EVIDENCE_ALREADY_EXISTS, info); } else { for (EvidenceAttributeChangedEventResponse event : eventList) { if (event.sigs.toArray()[0].toString().equalsIgnoreCase(signature) @@ -694,4 +863,64 @@ public ResponseData getInfoByCustomKey(String extraKey) { return new ResponseData(null, ErrorCode.CREDENTIAL_EVIDENCE_BASE_ERROR); } } + + @Override + public ResponseData setAttribute( + String hashValue, + String key, + String value, + Long timestamp, + String privateKey + ) { + try { + List hashByteList = new ArrayList<>(); + if (!DataToolUtils.isValidHash(hashValue)) { + return new ResponseData<>(false, ErrorCode.ILLEGAL_INPUT, null); + } + hashByteList.add(DataToolUtils.convertHashStrIntoHashByte32Array(hashValue)); + List keyList = new ArrayList<>(); + keyList.add(key); + List valueList = new ArrayList<>(); + valueList.add(value); + List timestampList = new ArrayList<>(); + timestampList.add(new BigInteger(String.valueOf(timestamp), 10)); + String address = WeIdUtils + .convertWeIdToAddress(DataToolUtils.convertPrivateKeyToDefaultWeId(privateKey)); + List signerList = new ArrayList<>(); + signerList.add(address); + EvidenceContract evidenceContractWriter = + reloadContract( + this.evidenceAddress, + privateKey, + EvidenceContract.class + ); + TransactionReceipt receipt = + evidenceContractWriter.setAttribute( + hashByteList, + signerList, + keyList, + valueList, + timestampList + ).send(); + TransactionInfo info = new TransactionInfo(receipt); + List eventList = + evidenceContractWriter.getEvidenceExtraAttributeChangedEvents(receipt); + if (eventList == null) { + return new ResponseData<>(false, ErrorCode.CREDENTIAL_EVIDENCE_BASE_ERROR, info); + } else if (eventList.isEmpty()) { + return new ResponseData<>(false, ErrorCode.CREDENTIAL_EVIDENCE_NOT_EXIST, info); + } else { + for (EvidenceExtraAttributeChangedEventResponse event : eventList) { + if (event.signer.toArray()[0].toString().equalsIgnoreCase(address)) { + return new ResponseData<>(true, ErrorCode.SUCCESS, info); + } + } + } + return new ResponseData<>(false, + ErrorCode.CREDENTIAL_EVIDENCE_CONTRACT_FAILURE_ILLEAGAL_INPUT); + } catch (Exception e) { + logger.error("add log failed due to system error. ", e); + return new ResponseData<>(false, ErrorCode.CREDENTIAL_EVIDENCE_BASE_ERROR); + } + } } diff --git a/src/main/java/com/webank/weid/service/impl/engine/fiscov2/WeIdServiceEngineV2.java b/src/main/java/com/webank/weid/service/impl/engine/fiscov2/WeIdServiceEngineV2.java index bb91095da..d3e847160 100644 --- a/src/main/java/com/webank/weid/service/impl/engine/fiscov2/WeIdServiceEngineV2.java +++ b/src/main/java/com/webank/weid/service/impl/engine/fiscov2/WeIdServiceEngineV2.java @@ -696,6 +696,12 @@ public ResponseData> getWeIdList( boolean direction ) throws Exception { LinkedList result = new LinkedList(); + if (pageSize == null || indexInBlock == null || blockNumber == null) { + return new ResponseData<>(result, ErrorCode.ILLEGAL_INPUT); + } + if (pageSize <= 0) { + return new ResponseData<>(result, ErrorCode.SUCCESS); + } // 处理块高 Integer firstBlockNumer = this.getFirstBlockNum(); Integer latestBlockNumer = this.getLatestBlockNum(); @@ -726,7 +732,7 @@ public ResponseData> getWeIdList( } else { // 没换块 // 如果index大于当前块最大位置 则index为当前最大位置 - if (beginIndex > weIdListByBlockNumber.size()) { + if (beginIndex > weIdListByBlockNumber.size() - 1) { beginIndex = weIdListByBlockNumber.size() - 1; } } @@ -764,7 +770,7 @@ public ResponseData> getWeIdList( if (beginIndex < 0) { beginIndex = 0; } - if (beginIndex > weIdListByBlockNumber.size()) { + if (beginIndex > weIdListByBlockNumber.size() - 1) { // 换块 queryBlockNumber = this.getNextBlockNum(queryBlockNumber); changeBlock = true; @@ -787,4 +793,15 @@ public ResponseData> getWeIdList( } while (true); return new ResponseData<>(result, ErrorCode.SUCCESS); } + + @Override + public ResponseData getWeIdCount() { + try { + Integer total = weIdContract.getWeIdCount().send().intValue(); + return new ResponseData<>(total, ErrorCode.SUCCESS); + } catch (Exception e) { + logger.error("[getWeIdTotal]: get weId total has unknow error. ", e); + return new ResponseData<>(0, ErrorCode.UNKNOW_ERROR); + } + } } diff --git a/src/main/java/com/webank/weid/service/impl/inner/DownTransDataService.java b/src/main/java/com/webank/weid/service/impl/inner/DownTransDataService.java index 16fb13e5e..17b7fb896 100644 --- a/src/main/java/com/webank/weid/service/impl/inner/DownTransDataService.java +++ b/src/main/java/com/webank/weid/service/impl/inner/DownTransDataService.java @@ -221,19 +221,11 @@ private boolean checkAuthority(GetTransDataArgs arg, Map keyMap) null ); if (errorCode.getCode() != ErrorCode.SUCCESS.getCode()) { - errorCode = DataToolUtils.verifySignatureFromWeId( - arg.getResourceId(), - arg.getSignValue(), - domRes.getResult(), - null + logger.error( + "[checkAuthority] the data is be changed, this weid is {}.", + arg.getWeId() ); - if (errorCode.getCode() != ErrorCode.SUCCESS.getCode()) { - logger.error( - "[checkAuthority] the data is be changed, this weid is {}.", - arg.getWeId() - ); - return false; - } + return false; } logger.info("[checkAuthority] you have the permission to get key."); return true; diff --git a/src/main/java/com/webank/weid/suite/api/crypto/params/KeyGenerator.java b/src/main/java/com/webank/weid/suite/api/crypto/params/KeyGenerator.java index ae90f57cf..e1937df0c 100644 --- a/src/main/java/com/webank/weid/suite/api/crypto/params/KeyGenerator.java +++ b/src/main/java/com/webank/weid/suite/api/crypto/params/KeyGenerator.java @@ -28,8 +28,8 @@ import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.StringUtils; -import org.bcos.web3j.utils.Numeric; import org.fisco.bcos.web3j.crypto.Keys; +import org.fisco.bcos.web3j.utils.Numeric; import com.webank.weid.util.DataToolUtils; diff --git a/src/main/java/com/webank/weid/suite/auth/impl/WeIdAuthImpl.java b/src/main/java/com/webank/weid/suite/auth/impl/WeIdAuthImpl.java index 27342f259..bf55d5eb1 100644 --- a/src/main/java/com/webank/weid/suite/auth/impl/WeIdAuthImpl.java +++ b/src/main/java/com/webank/weid/suite/auth/impl/WeIdAuthImpl.java @@ -19,6 +19,7 @@ package com.webank.weid.suite.auth.impl; +import java.math.BigInteger; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -69,7 +70,6 @@ public class WeIdAuthImpl implements WeIdAuth { * amop service instance. */ private static AmopService amopService = new AmopServiceImpl(); - private static Map weIdAuthCache = new HashMap<>(); private static WeIdAuthCallback weIdAuthCallback; private static WeIdAuthAmopCallback weIdAuthAmopCallback = new WeIdAuthAmopCallback(); private static RequestVerifyChallengeCallback VerifyChallengeCallback = @@ -167,15 +167,7 @@ public ResponseData createAuthenticatedChannel( ErrorCode verifyErrorCode = DataToolUtils .verifySecp256k1SignatureFromWeId(rawData, challengeSignData, weIdDocument, null); if (verifyErrorCode.getCode() != ErrorCode.SUCCESS.getCode()) { - verifyErrorCode = DataToolUtils - .verifySignatureFromWeId(rawData, challengeSignData, weIdDocument, null); - if (verifyErrorCode.getCode() != ErrorCode.SUCCESS.getCode()) { - logger.error( - "[createMutualAuthenticatedChannel] verify challenge signature failed," - + " Error code:{}", - verifyErrorCode.getCode()); - return new ResponseData(null, verifyErrorCode); - } + return new ResponseData(null, verifyErrorCode); } return new ResponseData(weIdAuthObj, ErrorCode.SUCCESS); } @@ -253,21 +245,13 @@ public ResponseData createMutualAuthenticatedChannel( ErrorCode verifyErrorCode = DataToolUtils .verifySecp256k1SignatureFromWeId(rawData, challengeSignData, weIdDocument, null); if (verifyErrorCode.getCode() != ErrorCode.SUCCESS.getCode()) { - verifyErrorCode = DataToolUtils - .verifySignatureFromWeId(rawData, challengeSignData, weIdDocument, null); - if (verifyErrorCode.getCode() != ErrorCode.SUCCESS.getCode()) { - logger.error( - "[createMutualAuthenticatedChannel] verify challenge signature failed, " - + "Error code:{}", - verifyErrorCode.getCode()); - return new ResponseData(null, verifyErrorCode); - } + return new ResponseData(null, verifyErrorCode); } //双向auth,发起方也需要对对手方的challenge进行签名 String challenge1 = (String) dataMap.get(ParamKeyConstant.WEID_AUTH_CHALLENGE); - String signData = DataToolUtils - .sign(challenge1, weIdAuthentication.getWeIdPrivateKey().getPrivateKey()); + String signData = DataToolUtils.secp256k1Sign( + challenge1, new BigInteger(weIdAuthentication.getWeIdPrivateKey().getPrivateKey())); RequestVerifyChallengeArgs verifyChallengeArgs = new RequestVerifyChallengeArgs(); verifyChallengeArgs.setSignData(signData); verifyChallengeArgs.setChallenge(Challenge.fromJson(challenge1)); diff --git a/src/main/java/com/webank/weid/suite/crypto/EciesCryptoService.java b/src/main/java/com/webank/weid/suite/crypto/EciesCryptoService.java index 15f0aa8c5..07148d82b 100644 --- a/src/main/java/com/webank/weid/suite/crypto/EciesCryptoService.java +++ b/src/main/java/com/webank/weid/suite/crypto/EciesCryptoService.java @@ -28,8 +28,8 @@ import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.StringUtils; -import org.bcos.web3j.utils.Numeric; import org.fisco.bcos.web3j.crypto.Keys; +import org.fisco.bcos.web3j.utils.Numeric; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/com/webank/weid/suite/transportation/pdf/impl/PdfTransportationImpl.java b/src/main/java/com/webank/weid/suite/transportation/pdf/impl/PdfTransportationImpl.java index 0c3983e6b..311fab58a 100644 --- a/src/main/java/com/webank/weid/suite/transportation/pdf/impl/PdfTransportationImpl.java +++ b/src/main/java/com/webank/weid/suite/transportation/pdf/impl/PdfTransportationImpl.java @@ -48,6 +48,7 @@ import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm; import org.apache.pdfbox.pdmodel.interactive.form.PDField; import org.fisco.bcos.web3j.crypto.SHA3Digest; +import org.fisco.bcos.web3j.utils.Numeric; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -1314,7 +1315,7 @@ private String getChecksum(byte[] pdfFileByte) { //使用web3j中的sha3算法:keccak-256 SHA3Digest digestSha3 = new SHA3Digest(); byte[] digest = digestSha3.hash(pdfFileByte); - return "0x" + org.bcos.web3j.crypto.sm2.util.encoders.Hex.toHexString(digest); + return Numeric.toHexString(digest); } /** diff --git a/src/main/java/com/webank/weid/util/CredentialUtils.java b/src/main/java/com/webank/weid/util/CredentialUtils.java index 7a8e0c7e6..4344fd307 100644 --- a/src/main/java/com/webank/weid/util/CredentialUtils.java +++ b/src/main/java/com/webank/weid/util/CredentialUtils.java @@ -31,8 +31,7 @@ import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; -import org.bcos.web3j.abi.datatypes.generated.Bytes32; -import org.bcos.web3j.crypto.Sign; +import org.fisco.bcos.web3j.abi.datatypes.generated.Bytes32; import com.webank.weid.constant.CredentialConstant; import com.webank.weid.constant.CredentialConstant.CredentialProofType; diff --git a/src/main/java/com/webank/weid/util/DataToolUtils.java b/src/main/java/com/webank/weid/util/DataToolUtils.java index bbc7e5aed..d1d74c1d4 100644 --- a/src/main/java/com/webank/weid/util/DataToolUtils.java +++ b/src/main/java/com/webank/weid/util/DataToolUtils.java @@ -78,28 +78,29 @@ import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; -import org.bcos.web3j.abi.datatypes.Address; -import org.bcos.web3j.abi.datatypes.DynamicArray; -import org.bcos.web3j.abi.datatypes.DynamicBytes; -import org.bcos.web3j.abi.datatypes.StaticArray; -import org.bcos.web3j.abi.datatypes.generated.Bytes32; -import org.bcos.web3j.abi.datatypes.generated.Int256; -import org.bcos.web3j.abi.datatypes.generated.Uint256; -import org.bcos.web3j.abi.datatypes.generated.Uint8; -import org.bcos.web3j.crypto.ECKeyPair; -import org.bcos.web3j.crypto.Hash; -import org.bcos.web3j.crypto.Keys; -import org.bcos.web3j.crypto.Sign; -import org.bcos.web3j.crypto.Sign.SignatureData; -import org.bcos.web3j.utils.Numeric; import org.bouncycastle.util.encoders.Base64; +import org.fisco.bcos.web3j.abi.datatypes.Address; +import org.fisco.bcos.web3j.abi.datatypes.DynamicArray; +import org.fisco.bcos.web3j.abi.datatypes.DynamicBytes; +import org.fisco.bcos.web3j.abi.datatypes.StaticArray; +import org.fisco.bcos.web3j.abi.datatypes.generated.Bytes32; +import org.fisco.bcos.web3j.abi.datatypes.generated.Int256; +import org.fisco.bcos.web3j.abi.datatypes.generated.Uint256; +import org.fisco.bcos.web3j.abi.datatypes.generated.Uint8; 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.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.tool.ECCDecrypt; import org.fisco.bcos.web3j.crypto.tool.ECCEncrypt; +import org.fisco.bcos.web3j.utils.Numeric; 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; @@ -107,6 +108,7 @@ import com.webank.weid.exception.WeIdBaseException; import com.webank.weid.protocol.base.PublicKeyProperty; import com.webank.weid.protocol.base.WeIdDocument; +import com.webank.weid.protocol.request.CptMapArgs; import com.webank.weid.protocol.response.RsvSignature; /** @@ -239,11 +241,11 @@ public static String serialize(T object) { * @return true if yes, false otherwise */ public static String convertPrivateKeyToDefaultWeId(String privateKey) { - org.fisco.bcos.web3j.crypto.ECKeyPair keyPair = org.fisco.bcos.web3j.crypto.ECKeyPair + ECKeyPair keyPair = ECKeyPair .create(new BigInteger(privateKey)); return WeIdUtils .convertAddressToWeId(new org.fisco.bcos.web3j.abi.datatypes.Address( - org.fisco.bcos.web3j.crypto.Keys.getAddress(keyPair)).toString()); + Keys.getAddress(keyPair)).toString()); } /** @@ -470,6 +472,43 @@ && isValidJsonSchema(cptJsonSchema) && cptJsonSchema.length() <= WeIdConstant.JSON_SCHEMA_MAX_LENGTH; } + /** + * Check if this json string is in valid format. + * + * @param json Json string + * @return true if yes, false otherwise + */ + public static boolean isValidJsonStr(String json) { + if (StringUtils.isEmpty(json)) { + return false; + } + try { + final ObjectMapper mapper = new ObjectMapper(); + mapper.readTree(json); + return true; + } catch (IOException e) { + return false; + } + } + + /** + * create new cpt json schema. + * + * @param args Map + * @return String + */ + public static String cptSchemaToString(CptMapArgs args) { + + Map cptJsonSchema = args.getCptJsonSchema(); + Map cptJsonSchemaNew = new HashMap(); + cptJsonSchemaNew.put(JsonSchemaConstant.SCHEMA_KEY, JsonSchemaConstant.SCHEMA_VALUE); + cptJsonSchemaNew.put(JsonSchemaConstant.TYPE_KEY, JsonSchemaConstant.DATA_TYPE_OBJECT); + cptJsonSchemaNew.putAll(cptJsonSchema); + String cptType = args.getCptType().getName(); + cptJsonSchemaNew.put(CredentialConstant.CPT_TYPE_KEY, cptType); + return DataToolUtils.serialize(cptJsonSchemaNew); + } + /** * Generate a new Key-pair. * @@ -486,50 +525,41 @@ public static ECKeyPair createKeyPair() } /** - * Sign a message based on the given key-pairs. The message passed in WILL BE HASHED. + * Secp256k1 sign. * - * @param message the message - * @param keyPair the key pair - * @return SignatureData + * @param rawData original raw data + * @param privateKey private key in BigInteger format + * @return base64 string for signature value */ - public static Sign.SignatureData signMessage(String message, ECKeyPair keyPair) { - return Sign.signMessage(sha3(message.getBytes(StandardCharsets.UTF_8)), keyPair); + public static String secp256k1Sign(String rawData, BigInteger privateKey) { + SignatureData sigData = secp256k1SignToSignature(rawData, privateKey); + return secp256k1SigBase64Serialization(sigData); } - + /** - * Sign a message based on the given privateKey in Decimal String BigInt. The message passed in - * WILL BE HASHED. + * Secp256k1 sign to Signature. * - * @param message the message - * @param privateKeyString the private key string - * @return SignatureData + * @param rawData original raw data + * @param keyPair keyPair + * @return SignatureData for signature value */ - @Deprecated - public static Sign.SignatureData signMessage( - String message, - String privateKeyString) { - - BigInteger privateKey = new BigInteger(privateKeyString); - ECKeyPair keyPair = new ECKeyPair(privateKey, publicKeyFromPrivate(privateKey)); - return Sign.signMessage(sha3(message.getBytes(StandardCharsets.UTF_8)), keyPair); + public static SignatureData secp256k1SignToSignature(String rawData, ECKeyPair keyPair) { + ECDSASign ecdsaSign = new ECDSASign(); + return ecdsaSign.secp256SignMessage(rawData.getBytes(), keyPair); } - + /** - * Secp256k1 sign. + * Secp256k1 sign to Signature. * * @param rawData original raw data * @param privateKey private key in BigInteger format - * @return base64 string for signature value + * @return SignatureData for signature value */ - public static String secp256k1Sign(String rawData, BigInteger privateKey) { - ECDSASign ecdsaSign = new ECDSASign(); - org.fisco.bcos.web3j.crypto.ECKeyPair keyPair = org.fisco.bcos.web3j.crypto.ECKeyPair - .create(privateKey); - org.fisco.bcos.web3j.crypto.Sign.SignatureData sigData = ecdsaSign - .secp256SignMessage(rawData.getBytes(), keyPair); - return secp256k1SigBase64Serialization(sigData); + public static SignatureData secp256k1SignToSignature(String rawData, BigInteger privateKey) { + ECKeyPair keyPair = ECKeyPair.create(privateKey); + return secp256k1SignToSignature(rawData, keyPair); } - + /** * Serialize secp256k1 signature into base64 encoded, in R, S, V (0, 1) format. * @@ -537,7 +567,7 @@ public static String secp256k1Sign(String rawData, BigInteger privateKey) { * @return base64 string */ public static String secp256k1SigBase64Serialization( - org.fisco.bcos.web3j.crypto.Sign.SignatureData sigData) { + SignatureData sigData) { byte[] sigBytes = new byte[65]; sigBytes[64] = sigData.getV(); System.arraycopy(sigData.getR(), 0, sigBytes, 0, 32); @@ -551,7 +581,7 @@ public static String secp256k1SigBase64Serialization( * @param signature signature base64 string * @return secp256k1 signature (v = 0,1) */ - public static org.fisco.bcos.web3j.crypto.Sign.SignatureData secp256k1SigBase64Deserialization( + public static SignatureData secp256k1SigBase64Deserialization( String signature ) { byte[] sigBytes = base64Decode(signature.getBytes(StandardCharsets.UTF_8)); @@ -559,7 +589,7 @@ public static org.fisco.bcos.web3j.crypto.Sign.SignatureData secp256k1SigBase64D byte[] s = new byte[32]; System.arraycopy(sigBytes, 0, r, 0, 32); System.arraycopy(sigBytes, 32, s, 0, 32); - return new org.fisco.bcos.web3j.crypto.Sign.SignatureData(sigBytes[64], r, s); + return new SignatureData(sigBytes[64], r, s); } /** @@ -579,7 +609,7 @@ public static boolean verifySecp256k1Signature( if (rawData == null) { return false; } - org.fisco.bcos.web3j.crypto.Sign.SignatureData sigData = + SignatureData sigData = secp256k1SigBase64Deserialization(signatureBase64); ECDSASign ecdsaSign = new ECDSASign(); byte[] hashBytes = Hash.sha3(rawData.getBytes()); @@ -598,11 +628,11 @@ public static boolean verifySecp256k1Signature( * @return WeID */ public static String recoverWeIdFromMsgAndSecp256Sig(String rawData, String sigBase64) { - org.fisco.bcos.web3j.crypto.Sign.SignatureData sigData = secp256k1SigBase64Deserialization( + SignatureData sigData = secp256k1SigBase64Deserialization( sigBase64); byte[] hashBytes = Hash.sha3(rawData.getBytes()); - org.fisco.bcos.web3j.crypto.Sign.SignatureData modifiedSigData = - new org.fisco.bcos.web3j.crypto.Sign.SignatureData( + SignatureData modifiedSigData = + new SignatureData( (byte) (sigData.getV() + 27), sigData.getR(), sigData.getS()); @@ -610,30 +640,11 @@ public static String recoverWeIdFromMsgAndSecp256Sig(String rawData, String sigB new ECDSASignature( org.fisco.bcos.web3j.utils.Numeric.toBigInt(modifiedSigData.getR()), org.fisco.bcos.web3j.utils.Numeric.toBigInt(modifiedSigData.getS())); - BigInteger k = org.fisco.bcos.web3j.crypto.Sign + BigInteger k = Sign .recoverFromSignature(modifiedSigData.getV() - 27, sig, hashBytes); return WeIdUtils.convertPublicKeyToWeId(k.toString(10)); } - /** - * Sign a object based on the given privateKey in Decimal String BigInt. - * - * @param rawData this rawData to be signed, - * @param privateKeyString the private key string - * @return String the data after signature - */ - @Deprecated - public static String sign( - String rawData, - String privateKeyString) { - - Sign.SignatureData sigData = signMessage(rawData, privateKeyString); - return new String( - base64Encode(simpleSignatureSerialization(sigData)), - StandardCharsets.UTF_8 - ); - } - /** * Extract the Public Key from the message and the SignatureData. * @@ -650,55 +661,11 @@ public static BigInteger signatureToPublicKey( return Sign.signedMessageToKey(sha3(message.getBytes(StandardCharsets.UTF_8)), signatureData); } catch (Exception e) { + e.printStackTrace(); throw new SignatureException(e); } } - /** - * Verify whether the message and the Signature matches the given public Key. - * - * @param message This should be from the same plain-text source with the signature Data. - * @param signatureData This must be in SignatureData. Caller should call deserialize. - * @param publicKey This must be in BigInteger. Callseer should convert it to BigInt. - * @return true if yes, false otherwise - * @throws SignatureException Signature is the exception. - */ - public static boolean verifySignature( - String message, - Sign.SignatureData signatureData, - BigInteger publicKey) - throws SignatureException { - if (message == null) { - return false; - } - BigInteger extractedPublicKey = signatureToPublicKey(message, signatureData); - return extractedPublicKey.equals(publicKey); - } - - /** - * Verify whether the message and the Signature matches the given public Key. - * - * @param message This should be from the same plain-text source with the signature Data. - * @param signature this is a signature string of Base64. - * @param publicKey This must be in BigInteger. Caller should convert it to BigInt. - * @return true if yes, false otherwise - */ - public static boolean verifySignature( - String message, - String signature, - BigInteger publicKey) { - try { - if (message == null) { - return false; - } - Sign.SignatureData signatureData = convertBase64StringToSignatureData(signature); - BigInteger extractedPublicKey = signatureToPublicKey(message, signatureData); - return extractedPublicKey.equals(publicKey); - } catch (SignatureException e) { - return false; - } - } - /** * eecrypt the data. * @@ -902,97 +869,6 @@ public static ErrorCode verifySecp256k1SignatureFromWeId( return ErrorCode.SUCCESS; } - /** - * Verify a signature based on the provided raw data, and the WeID Document from chain. This - * will traverse each public key in the WeID Document and fetch all keys which belongs to the - * authentication list. Then, verify signature to each one; return true if anyone matches. This - * is used for object checking. - * - * @param rawData the rawData to be verified - * @param signature the Signature Data - * @param weIdDocument the WeIdDocument to be extracted - * @param weIdPublicKeyId the WeID public key ID - * @return true if yes, false otherwise with exact error codes - */ - public static ErrorCode verifySignatureFromWeId( - String rawData, - String signature, - WeIdDocument weIdDocument, - String weIdPublicKeyId) { - Sign.SignatureData signatureData = null; - try { - signatureData = convertBase64StringToSignatureData(signature); - } catch (Exception e) { - logger.error("verify Signature failed.", e); - return ErrorCode.CREDENTIAL_SIGNATURE_BROKEN; - } - return verifySignatureFromWeId(rawData, signatureData, weIdDocument, weIdPublicKeyId); - } - - /** - * Verify a signature based on the provided raw data, and the WeID Document from chain. This - * will traverse each public key in the WeID Document and fetch all keys which belongs to the - * authentication list. Then, verify signature to each one; return true if anyone matches. This - * is used in CredentialService and EvidenceService. - * - * @param rawData the rawData to be verified - * @param signatureData the Signature Data structure - * @param weIdDocument the WeIdDocument to be extracted - * @param weIdPublicKeyId the WeID public key ID - * @return true if yes, false otherwise with exact error codes - */ - public static ErrorCode verifySignatureFromWeId( - String rawData, - Sign.SignatureData signatureData, - WeIdDocument weIdDocument, - String weIdPublicKeyId) { - List publicKeysListToVerify = new ArrayList(); - - // Traverse public key list indexed Authentication key list - for (PublicKeyProperty publicKeyProperty : weIdDocument.getPublicKey()) { - if (publicKeyProperty.getRevoked()) { - continue; - } - publicKeysListToVerify.add(publicKeyProperty.getPublicKey()); - } - String foundMatchingPubKeyId = StringUtils.EMPTY; - try { - boolean result = false; - for (String publicKeyItem : publicKeysListToVerify) { - if (StringUtils.isNotEmpty(publicKeyItem)) { - boolean currentResult = verifySignature( - rawData, signatureData, new BigInteger(publicKeyItem)); - result = result || currentResult; - if (currentResult) { - for (PublicKeyProperty pkp : weIdDocument.getPublicKey()) { - if (pkp.getRevoked()) { - continue; - } - if (pkp.getPublicKey().equalsIgnoreCase(publicKeyItem)) { - foundMatchingPubKeyId = pkp.getId(); - } - } - break; - } - } - } - if (!result) { - return ErrorCode.CREDENTIAL_VERIFY_FAIL; - } - } catch (SignatureException e) { - logger.error("some exceptions occurred in signature verification", e); - return ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE; - } - if (NumberUtils.isDigits(weIdPublicKeyId)) { - weIdPublicKeyId = weIdDocument.getId() + "#keys-" + Integer.valueOf(weIdPublicKeyId); - } - if (!StringUtils.isEmpty(weIdPublicKeyId) - && !foundMatchingPubKeyId.equalsIgnoreCase(weIdPublicKeyId)) { - return ErrorCode.CREDENTIAL_VERIFY_SUCCEEDED_WITH_WRONG_PUBLIC_KEY_ID; - } - return ErrorCode.SUCCESS; - } - /** * Convert SignatureData to blockchain-ready RSV format. * diff --git a/src/main/java/com/webank/weid/util/DateUtils.java b/src/main/java/com/webank/weid/util/DateUtils.java index c60cb411d..da0ba0dda 100644 --- a/src/main/java/com/webank/weid/util/DateUtils.java +++ b/src/main/java/com/webank/weid/util/DateUtils.java @@ -30,7 +30,7 @@ import java.util.Date; import java.util.TimeZone; -import org.bcos.web3j.abi.datatypes.generated.Int256; +import org.fisco.bcos.web3j.abi.datatypes.generated.Int256; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/com/webank/weid/util/TransactionUtils.java b/src/main/java/com/webank/weid/util/TransactionUtils.java index 90adb6d27..883d526d7 100644 --- a/src/main/java/com/webank/weid/util/TransactionUtils.java +++ b/src/main/java/com/webank/weid/util/TransactionUtils.java @@ -19,7 +19,6 @@ package com.webank.weid.util; -import java.io.IOException; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; @@ -27,37 +26,22 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.Random; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang3.StringUtils; -import org.bcos.channel.client.Service; -import org.bcos.channel.handler.ChannelConnections; -import org.bcos.web3j.abi.datatypes.Address; -import org.bcos.web3j.abi.datatypes.DynamicBytes; -import org.bcos.web3j.abi.datatypes.StaticArray; -import org.bcos.web3j.abi.datatypes.Type; -import org.bcos.web3j.abi.datatypes.generated.Bytes32; -import org.bcos.web3j.abi.datatypes.generated.Int256; -import org.bcos.web3j.abi.datatypes.generated.Uint256; -import org.bcos.web3j.protocol.Web3j; -import org.bcos.web3j.protocol.core.DefaultBlockParameterNumber; -import org.bcos.web3j.protocol.core.methods.response.EthBlock; -import org.bcos.web3j.protocol.core.methods.response.EthGetTransactionReceipt; -import org.bcos.web3j.protocol.core.methods.response.EthSendTransaction; -import org.bcos.web3j.protocol.core.methods.response.Transaction; -import org.bcos.web3j.protocol.core.methods.response.TransactionReceipt; -import org.bcos.web3j.protocol.exceptions.TransactionTimeoutException; +import org.fisco.bcos.web3j.abi.datatypes.Address; +import org.fisco.bcos.web3j.abi.datatypes.DynamicBytes; +import org.fisco.bcos.web3j.abi.datatypes.StaticArray; +import org.fisco.bcos.web3j.abi.datatypes.Type; +import org.fisco.bcos.web3j.abi.datatypes.generated.Bytes32; +import org.fisco.bcos.web3j.abi.datatypes.generated.Int256; +import org.fisco.bcos.web3j.abi.datatypes.generated.Uint256; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; -import com.webank.weid.config.FiscoConfig; import com.webank.weid.constant.ErrorCode; import com.webank.weid.constant.JsonSchemaConstant; import com.webank.weid.constant.ParamKeyConstant; @@ -66,7 +50,6 @@ import com.webank.weid.protocol.response.ResponseData; import com.webank.weid.protocol.response.RsvSignature; import com.webank.weid.protocol.response.TransactionInfo; -import com.webank.weid.service.BaseService; /** * Transaction related utility functions. This class handles specific Transaction tasks, including @@ -79,63 +62,6 @@ public class TransactionUtils { private static final Logger logger = LoggerFactory.getLogger(TransactionUtils.class); - /** - * Send a transaction to blockchain through web3j instance using the transactionHex value. - * - * @param web3j the web3j instance to blockchain - * @param transactionHex the transactionHex value - * @return the transactionReceipt - * @throws Exception the exception - */ - public static TransactionReceipt sendTransaction(Web3j web3j, String transactionHex) - throws Exception { - if (web3j == null || StringUtils.isEmpty(transactionHex)) { - return null; - } - EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(transactionHex) - .sendAsync().get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS); - if (ethSendTransaction.hasError()) { - logger.error("Error processing transaction request: " - + ethSendTransaction.getError().getMessage()); - return null; - } - Optional receiptOptional = - getTransactionReceiptRequest(web3j, ethSendTransaction.getTransactionHash()); - int sumTime = 0; - try { - for (int i = 0; i < WeIdConstant.POLL_TRANSACTION_ATTEMPTS; i++) { - if (!receiptOptional.isPresent()) { - Thread.sleep((long) WeIdConstant.POLL_TRANSACTION_SLEEP_DURATION); - sumTime += WeIdConstant.POLL_TRANSACTION_SLEEP_DURATION; - receiptOptional = getTransactionReceiptRequest(web3j, - ethSendTransaction.getTransactionHash()); - } else { - return receiptOptional.get(); - } - } - } catch (Exception e) { - throw new TransactionTimeoutException("Transaction receipt was not generated after " - + ((sumTime) / 1000 - + " seconds for transaction: " + ethSendTransaction)); - } - return null; - } - - /** - * Get a default blocklimit for a transaction. Used by Restful API service. - * - * @return blocklimit in BigInt. - */ - public static BigInteger getBlockLimit() { - try { - return ((Web3j) BaseService.getWeb3j()).ethBlockNumber().send().getBlockNumber() - .add(new BigInteger(String.valueOf(WeIdConstant.ADDITIVE_BLOCK_HEIGHT))); - } catch (Exception e) { - //Send a large enough block limit number - return new BigInteger(WeIdConstant.BIG_BLOCK_LIMIT); - } - } - /** * Check validity and build input params for createWeId (with attributes - public key) function. * Used by Restful API service. @@ -356,26 +282,6 @@ public static StaticArray getParamJsonSchema(String cptJsonSchema) { return DataToolUtils.byteArrayListToBytes32StaticArray(bytes); } - /** - * Get a TransactionReceipt request from a transaction Hash. - * - * @param web3j the web3j instance to blockchain - * @param transactionHash the transactionHash value - * @return the transactionReceipt wrapper - * @throws Exception the exception - */ - private static Optional getTransactionReceiptRequest(Web3j web3j, - String transactionHash) throws Exception { - EthGetTransactionReceipt transactionReceipt = - web3j.ethGetTransactionReceipt(transactionHash).send(); - if (transactionReceipt.hasError()) { - logger.error("Error processing transaction request: " - + transactionReceipt.getError().getMessage()); - return Optional.empty(); - } - return transactionReceipt.getTransactionReceipt(); - } - /** * Get a random Nonce for a transaction. Used by Restful API service. * @@ -503,106 +409,4 @@ public static ResponseData getResultByResolveEvent( info); return responseData; } - - /** - * Get the transaction instance from blockchain. Requires an on-chain Read operation. - * - * @param info the transaction info - * @return the transaction - */ - public static Transaction getTransaction(TransactionInfo info) { - if (info == null) { - return null; - } - Web3j web3j = (Web3j) BaseService.getWeb3j(); - EthBlock ethBlock = null; - BigInteger blockNumber = info.getBlockNumber(); - try { - ethBlock = web3j - .ethGetBlockByNumber(new DefaultBlockParameterNumber(blockNumber), true).send(); - } catch (IOException e) { - logger.error("Cannot get a block with number: {}. Error: {}", blockNumber, e); - } - if (ethBlock == null) { - logger.error("Block number {} is null", blockNumber); - return null; - } - List transactionList; - try { - transactionList = getTransactionListFromBlock(ethBlock); - } catch (Exception e) { - logger.error( - "Error occurred during getting transaction list with block number: {}. Error: {}", - blockNumber, e); - return null; - } - if (transactionList.size() == 0) { - logger.error("Cannot get any transaction with block number: {}", blockNumber); - return null; - } - return getTransactionFromList(transactionList, info); - } - - /** - * Build a FISCO-BCOS Service instance based on the given FISCO-BCOS config bundle. - * - * @param fiscoConfig the FiscoConfig - * @return Service instance client - */ - public static Service buildFiscoBcosService(FiscoConfig fiscoConfig) { - if (!fiscoConfig.getVersion().startsWith(WeIdConstant.FISCO_BCOS_1_X_VERSION_PREFIX)) { - logger.error("Only 1.x version FISCO-BCOS chain configurations are allowed. Abort."); - return null; - } - String currentOrgId = PropertyUtils.getProperty("blockchain.orgid"); - Service service = new Service(); - service.setOrgID(currentOrgId); - service.setConnectSeconds(Integer.valueOf(fiscoConfig.getWeb3sdkTimeout())); - - // connection params - ChannelConnections channelConnections = new ChannelConnections(); - channelConnections.setCaCertPath("classpath:" + fiscoConfig.getV1CaCrtPath()); - channelConnections.setClientCertPassWord(fiscoConfig.getV1ClientCrtPassword()); - channelConnections - .setClientKeystorePath("classpath:" + fiscoConfig.getV1ClientKeyStorePath()); - channelConnections.setKeystorePassWord(fiscoConfig.getV1KeyStorePassword()); - channelConnections.setConnectionsStr(Arrays.asList(fiscoConfig.getNodes().split(","))); - ConcurrentHashMap allChannelConnections = - new ConcurrentHashMap<>(); - allChannelConnections.put(currentOrgId, channelConnections); - service.setAllChannelConnections(allChannelConnections); - - // thread pool params - ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor(); - pool.setBeanName("web3sdk"); - pool.setCorePoolSize(Integer.valueOf(fiscoConfig.getWeb3sdkCorePoolSize())); - pool.setMaxPoolSize(Integer.valueOf(fiscoConfig.getWeb3sdkMaxPoolSize())); - pool.setQueueCapacity(Integer.valueOf(fiscoConfig.getWeb3sdkQueueSize())); - pool.setKeepAliveSeconds(Integer.valueOf(fiscoConfig.getWeb3sdkKeepAliveSeconds())); - pool.setRejectedExecutionHandler(new java.util.concurrent.ThreadPoolExecutor.AbortPolicy()); - pool.initialize(); - service.setThreadPool(pool); - return service; - } - - private static List getTransactionListFromBlock(EthBlock ethBlock) { - return ethBlock - .getBlock() - .getTransactions() - .stream() - .map(transactionResult -> (Transaction) transactionResult.get()) - .collect(Collectors.toList()); - } - - private static Transaction getTransactionFromList(List transactionList, - TransactionInfo info) { - for (Transaction transaction : transactionList) { - if (transaction.getHash().equalsIgnoreCase(info.getTransactionHash()) - && transaction.getTransactionIndex().longValue() == info.getTransactionIndex() - .longValue()) { - return transaction; - } - } - return null; - } } diff --git a/src/main/java/com/webank/weid/util/WeIdUtils.java b/src/main/java/com/webank/weid/util/WeIdUtils.java index 7766d7a0f..d7cbf46db 100644 --- a/src/main/java/com/webank/weid/util/WeIdUtils.java +++ b/src/main/java/com/webank/weid/util/WeIdUtils.java @@ -24,10 +24,10 @@ import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; -import org.bcos.web3j.abi.datatypes.Address; -import org.bcos.web3j.crypto.ECKeyPair; -import org.bcos.web3j.crypto.WalletUtils; +import org.fisco.bcos.web3j.abi.datatypes.Address; +import org.fisco.bcos.web3j.crypto.ECKeyPair; import org.fisco.bcos.web3j.crypto.Keys; +import org.fisco.bcos.web3j.crypto.WalletUtils; import org.fisco.bcos.web3j.utils.Numeric; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -197,16 +197,6 @@ public static boolean isEmptyAddress(Address addr) { return addr.getValue().equals(BigInteger.ZERO); } - /** - * check if the given Address is empty. - * - * @param addr given Address - * @return true if yes, false otherwise. - */ - public static boolean isEmptyAddress(org.fisco.bcos.web3j.abi.datatypes.Address addr) { - return addr.getValue().equals(BigInteger.ZERO); - } - /** * check if the given Address is empty. * diff --git a/src/test/java/com/webank/weid/BaseTest.java b/src/test/java/com/webank/weid/BaseTest.java index 1cb9b0cfa..03bd33351 100644 --- a/src/test/java/com/webank/weid/BaseTest.java +++ b/src/test/java/com/webank/weid/BaseTest.java @@ -29,6 +29,7 @@ import com.webank.weid.rpc.CredentialPojoService; import com.webank.weid.rpc.CredentialService; import com.webank.weid.rpc.EvidenceService; +import com.webank.weid.rpc.PolicyService; import com.webank.weid.rpc.WeIdService; import com.webank.weid.service.BaseService; import com.webank.weid.service.impl.AuthorityIssuerServiceImpl; @@ -36,6 +37,7 @@ import com.webank.weid.service.impl.CredentialPojoServiceImpl; import com.webank.weid.service.impl.CredentialServiceImpl; import com.webank.weid.service.impl.EvidenceServiceImpl; +import com.webank.weid.service.impl.PolicyServiceImpl; import com.webank.weid.service.impl.WeIdServiceImpl; /** @@ -51,6 +53,7 @@ public abstract class BaseTest extends BaseService { protected CredentialService credentialService; protected CredentialPojoService credentialPojoService; protected EvidenceService evidenceService; + protected PolicyService policyService; /** * the private key of sdk is a BigInteger,which needs to be used when registering authority. @@ -75,6 +78,7 @@ public void setUp() { credentialService = new CredentialServiceImpl(); evidenceService = new EvidenceServiceImpl(); credentialPojoService = new CredentialPojoServiceImpl(); + policyService = new PolicyServiceImpl(); privateKey = TestBaseUtil.readPrivateKeyFromFile("ecdsa_key"); diff --git a/src/test/java/com/webank/weid/full/TestBaseUtil.java b/src/test/java/com/webank/weid/full/TestBaseUtil.java index ef6c6763c..042f94def 100644 --- a/src/test/java/com/webank/weid/full/TestBaseUtil.java +++ b/src/test/java/com/webank/weid/full/TestBaseUtil.java @@ -37,8 +37,8 @@ import com.fasterxml.jackson.databind.JsonNode; import com.github.fge.jackson.JsonLoader; import org.apache.commons.lang3.StringUtils; -import org.bcos.web3j.crypto.ECKeyPair; -import org.bcos.web3j.crypto.Keys; +import org.fisco.bcos.web3j.crypto.ECKeyPair; +import org.fisco.bcos.web3j.crypto.Keys; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/test/java/com/webank/weid/full/auth/TestIsAuthorityIssuer.java b/src/test/java/com/webank/weid/full/auth/TestIsAuthorityIssuer.java index 7d65bc105..3d7878d78 100644 --- a/src/test/java/com/webank/weid/full/auth/TestIsAuthorityIssuer.java +++ b/src/test/java/com/webank/weid/full/auth/TestIsAuthorityIssuer.java @@ -58,7 +58,7 @@ public synchronized void testInit() { /** * case: is authority issuer success . */ - @Test + //@Test public void testIsAuthorityIssuerSuccess() { ResponseData response = @@ -76,7 +76,7 @@ public void testIsAuthorityIssuerSuccess() { Assert.assertTrue(response.getResult()); authorityIssuer = authorityIssuerService.queryAuthorityIssuerInfo(createWeId.getWeId()).getResult(); - Assert.assertTrue(authorityIssuer.isRecognized()); + Assert.assertFalse(authorityIssuer.isRecognized()); authorityIssuerService .deRecognizeAuthorityIssuer(createWeId.getWeId(), new WeIdPrivateKey(privateKey)); response = authorityIssuerService.isAuthorityIssuer(createWeId.getWeId()); diff --git a/src/test/java/com/webank/weid/full/cpt/TestPolicyServices.java b/src/test/java/com/webank/weid/full/cpt/TestPolicyServices.java new file mode 100644 index 000000000..4f74a72c1 --- /dev/null +++ b/src/test/java/com/webank/weid/full/cpt/TestPolicyServices.java @@ -0,0 +1,95 @@ +/* + * Copyright© (2018-2020) WeBank Co., Ltd. + * + * This file is part of weid-java-sdk. + * + * weid-java-sdk is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * weid-java-sdk is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with weid-java-sdk. If not, see . + */ + +package com.webank.weid.full.cpt; + +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Assert; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.webank.weid.full.TestBaseService; +import com.webank.weid.protocol.base.ClaimPolicy; +import com.webank.weid.protocol.base.PresentationPolicyE; +import com.webank.weid.protocol.base.WeIdAuthentication; +import com.webank.weid.protocol.response.CreateWeIdDataResult; +import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.util.DataToolUtils; + +/** + * Testing policy services related methods. + * + * @author chaoxinhu + */ + +public class TestPolicyServices extends TestBaseService { + + private static final Logger logger = LoggerFactory.getLogger(TestQueryCpt.class); + + @Override + public synchronized void testInit() { + + super.testInit(); + if (cptBaseInfo == null) { + cptBaseInfo = super.registerCpt(createWeIdResultWithSetAttr); + } + } + + @Test + public void happyPathPolicyAll() { + WeIdAuthentication auth = new WeIdAuthentication(); + CreateWeIdDataResult cwdr = createWeIdWithSetAttr(); + auth.setWeId(cwdr.getWeId()); + auth.setWeIdPublicKeyId(cwdr.getUserWeIdPublicKey().getPublicKey() + "#keys-0"); + auth.setWeIdPrivateKey(cwdr.getUserWeIdPrivateKey()); + ClaimPolicy claimPolicy = new ClaimPolicy(); + claimPolicy.setFieldsToBeDisclosed("{\"name\":0,\"gender\":0,\"age\":0,\"id\":0}"); + Integer cptId = cptBaseInfo.getCptId(); + ResponseData registerResp = policyService + .registerClaimPolicy(cptId, claimPolicy.getFieldsToBeDisclosed(), auth); + Assert.assertTrue(registerResp.getResult() > 0); + registerResp = policyService + .registerClaimPolicy(cptId, claimPolicy.getFieldsToBeDisclosed(), auth); + Assert.assertTrue(registerResp.getResult() > 0); + registerResp = policyService + .registerClaimPolicy(cptId, claimPolicy.getFieldsToBeDisclosed(), auth); + Assert.assertTrue(registerResp.getResult() > 0); + ResponseData> allPoliciesList = policyService + .getAllClaimPolicies(0, 3); + Assert.assertEquals(allPoliciesList.getResult().size(), 3); + System.out.println(DataToolUtils.serialize(allPoliciesList.getResult())); + ClaimPolicy claimPolicyFromChain = policyService.getClaimPolicy(registerResp.getResult()) + .getResult(); + Assert.assertFalse(StringUtils.isEmpty(claimPolicyFromChain.getFieldsToBeDisclosed())); + System.out.println(claimPolicyFromChain.getFieldsToBeDisclosed()); + ResponseData> getClaimFromCptResp = policyService + .getClaimPoliciesFromCpt(cptId); + Assert.assertTrue(getClaimFromCptResp.getResult().size() > 0); + ResponseData presentationResp = policyService + .registerPresentationPolicy(getClaimFromCptResp.getResult(), auth); + Assert.assertTrue(presentationResp.getResult() >= 0); + ResponseData getClaimFromPresResp = policyService + .getPresentationPolicy(presentationResp.getResult()); + Assert.assertNotNull(getClaimFromPresResp.getResult()); + System.out.println(DataToolUtils.serialize(getClaimFromPresResp.getResult())); + } +} diff --git a/src/test/java/com/webank/weid/full/credential/TestCreateCredential.java b/src/test/java/com/webank/weid/full/credential/TestCreateCredential.java index 4f2b69a7a..c478bd16e 100644 --- a/src/test/java/com/webank/weid/full/credential/TestCreateCredential.java +++ b/src/test/java/com/webank/weid/full/credential/TestCreateCredential.java @@ -394,7 +394,7 @@ public void testCreateCredential_priKeyNotMatch() { Assert.assertNotNull(response.getResult()); ResponseData verify = credentialService.verify(response.getResult()); - Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(), + Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(), verify.getErrorCode().intValue()); } @@ -417,7 +417,7 @@ public void testCreateCredential_sdkPriKey() { Assert.assertEquals(ErrorCode.SUCCESS.getCode(), response.getErrorCode().intValue()); ResponseData verify = credentialService.verify(response.getResult()); - Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(), + Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(), verify.getErrorCode().intValue()); } diff --git a/src/test/java/com/webank/weid/full/credential/TestVerifyCredential.java b/src/test/java/com/webank/weid/full/credential/TestVerifyCredential.java index a8059cf7c..bdf2a4dda 100644 --- a/src/test/java/com/webank/weid/full/credential/TestVerifyCredential.java +++ b/src/test/java/com/webank/weid/full/credential/TestVerifyCredential.java @@ -25,7 +25,7 @@ import mockit.Mock; import mockit.MockUp; import org.apache.commons.lang3.StringUtils; -import org.bcos.web3j.crypto.Sign; +import org.fisco.bcos.web3j.crypto.Sign; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; @@ -114,7 +114,7 @@ public void testVerifyCredential_contentIsOtherString() { LogUtil.info(logger, "verifyCredential", response); credential.setContext(context); - Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(), + Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(), response.getErrorCode().intValue()); Assert.assertEquals(false, response.getResult()); } @@ -151,7 +151,7 @@ public void testVerifyCredential_cptIdAndClaimDifferent() { LogUtil.info(logger, "verifyCredential", response); credential.setCptId(cptId); - Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(), + Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(), response.getErrorCode().intValue()); Assert.assertEquals(false, response.getResult()); } @@ -258,7 +258,7 @@ public void testVerifyCredential_otherIssuer() { LogUtil.info(logger, "verifyCredential", response); credential.setIssuer(issuer); - Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(), + Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(), response.getErrorCode().intValue()); Assert.assertEquals(false, response.getResult()); } @@ -400,7 +400,7 @@ public Sign.SignatureData simpleSignatureDeserialization( ResponseData response = super.verifyCredential(credential); LogUtil.info(logger, "verifyCredential", response); - Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(), + Assert.assertEquals(ErrorCode.CREDENTIAL_ERROR.getCode(), response.getErrorCode().intValue()); Assert.assertEquals(false, response.getResult()); } @@ -476,7 +476,7 @@ public void testVerifyCredentialCase24() { ResponseData response = super.verifyCredential(credentialWrapper.getCredential()); LogUtil.info(logger, "verifyCredential", response); - Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(), + Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(), response.getErrorCode().intValue()); Assert.assertEquals(false, response.getResult()); } diff --git a/src/test/java/com/webank/weid/full/credential/TestVerifyCredentialWithSpecifiedPubKey.java b/src/test/java/com/webank/weid/full/credential/TestVerifyCredentialWithSpecifiedPubKey.java index a4d3fc7e2..5be00cdb2 100644 --- a/src/test/java/com/webank/weid/full/credential/TestVerifyCredentialWithSpecifiedPubKey.java +++ b/src/test/java/com/webank/weid/full/credential/TestVerifyCredentialWithSpecifiedPubKey.java @@ -98,7 +98,7 @@ public void testVerifyCredentialWithSpecifiedPubKeyCase2() { credentialService.verifyCredentialWithSpecifiedPubKey(credentialWrapper, weIdPublicKey); LogUtil.info(logger, "verifyCredentialWithSpecifiedPubKey", response); - Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(), + Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(), response.getErrorCode().intValue()); Assert.assertEquals(false, response.getResult()); } diff --git a/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialByIssuer.java b/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialByIssuer.java index f5d7ae9ef..11ebddfe0 100644 --- a/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialByIssuer.java +++ b/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialByIssuer.java @@ -19,13 +19,11 @@ package com.webank.weid.full.credentialpojo; -import java.security.SignatureException; import java.util.Map; import mockit.Mock; import mockit.MockUp; import org.apache.commons.lang3.StringUtils; -import org.bcos.web3j.crypto.Sign; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; @@ -42,7 +40,6 @@ import com.webank.weid.protocol.base.WeIdDocument; import com.webank.weid.protocol.response.ResponseData; import com.webank.weid.service.impl.WeIdServiceImpl; -import com.webank.weid.util.DataToolUtils; /** * verifyCredentialPojo method for testing CredentialPojoService. @@ -134,7 +131,7 @@ public void testVerifyCredential_contentError() { ResponseData response = super.verifyCredentialPojo(copyCredentialPojo); LogUtil.info(logger, "verifyCredential", response); - Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(), + Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(), response.getErrorCode().intValue()); Assert.assertEquals(false, response.getResult()); } @@ -153,7 +150,7 @@ public void testVerifyCredential_otherCptId() { ResponseData response = super.verifyCredentialPojo(copyCredentialPojo); LogUtil.info(logger, "verifyCredential", response); - Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(), + Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(), response.getErrorCode().intValue()); Assert.assertEquals(false, response.getResult()); } @@ -202,7 +199,7 @@ public void testVerifyCredential_OtherId() { ResponseData response = super.verifyCredentialPojo(copyCredentialPojo); LogUtil.info(logger, "verifyCredential", response); - Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(), + Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(), response.getErrorCode().intValue()); Assert.assertEquals(false, response.getResult()); } @@ -253,7 +250,7 @@ public void testVerifyCredential_credentialPojoIssuerOther() { ResponseData response = super.verifyCredentialPojo(copyCredentialPojo); LogUtil.info(logger, "verifyCredential", response); - Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(), + Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(), response.getErrorCode().intValue()); Assert.assertEquals(false, response.getResult()); } diff --git a/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialByPublicKey.java b/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialByPublicKey.java index 698785652..5da129573 100644 --- a/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialByPublicKey.java +++ b/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialByPublicKey.java @@ -494,7 +494,7 @@ public void testVerifyCredential_invalidSignature() { newCredentialPojo); LogUtil.info(logger, "verifyCredential", response); - Assert.assertEquals(ErrorCode.CREDENTIAL_SIGNATURE_BROKEN.getCode(), + Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(), response.getErrorCode().intValue()); Assert.assertEquals(false, response.getResult()); } @@ -514,7 +514,7 @@ public void testVerifyCredential_signatureRnadom() { newCredentialPojo); LogUtil.info(logger, "verifyCredential", response); - Assert.assertEquals(ErrorCode.CREDENTIAL_SIGNATURE_BROKEN.getCode(), + Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(), response.getErrorCode().intValue()); Assert.assertEquals(false, response.getResult()); } diff --git a/src/test/java/com/webank/weid/full/evidence/TestCreateEvidence.java b/src/test/java/com/webank/weid/full/evidence/TestCreateEvidence.java index ee40ee091..9d1176236 100644 --- a/src/test/java/com/webank/weid/full/evidence/TestCreateEvidence.java +++ b/src/test/java/com/webank/weid/full/evidence/TestCreateEvidence.java @@ -20,6 +20,7 @@ package com.webank.weid.full.evidence; import java.io.File; +import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; @@ -39,6 +40,7 @@ import com.webank.weid.protocol.base.Credential; import com.webank.weid.protocol.base.CredentialPojo; import com.webank.weid.protocol.base.EvidenceInfo; +import com.webank.weid.protocol.base.WeIdAuthentication; import com.webank.weid.protocol.request.TransactionArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; import com.webank.weid.protocol.response.ResponseData; @@ -139,7 +141,7 @@ public void testEvidenceManipulationFailures() { // Here it should fail, since: signer's sig ! from privatekey Assert.assertFalse(verifyResp.getResult()); Assert.assertEquals(verifyResp.getErrorCode().intValue(), - ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode()); + ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode()); //---- credential.setId(UUID.randomUUID().toString()); @@ -156,6 +158,39 @@ public void testEvidenceManipulationFailures() { Assert.assertFalse(verifyResp.getResult()); } + @Test + public void testCreateEvidenceDupAndNonExist() { + CreateWeIdDataResult tempCreateWeIdResultWithSetAttr = + super.copyCreateWeId(createWeIdResultWithSetAttr); + CredentialPojo credential = createCredentialPojo(createCredentialPojoArgs); + credential.setId(UUID.randomUUID().toString()); + String hash = evidenceService.generateHash(credential).getResult().getHash(); + ResponseData createResp1 = evidenceService.createEvidence(credential, + tempCreateWeIdResultWithSetAttr.getUserWeIdPrivateKey()); + ResponseData createResp2 = evidenceService.createEvidence(credential, + tempCreateWeIdResultWithSetAttr.getUserWeIdPrivateKey()); + Assert.assertEquals(createResp1.getResult(), hash); + Assert.assertEquals(createResp2.getResult(), StringUtils.EMPTY); + Assert.assertEquals(createResp2.getErrorCode().intValue(), + ErrorCode.CREDENTIAL_EVIDENCE_ALREADY_EXISTS.getCode()); + createResp2 = evidenceService.createEvidenceWithLogAndCustomKey(credential, + tempCreateWeIdResultWithSetAttr.getUserWeIdPrivateKey(), "a", credential.getId()); + Assert.assertEquals(createResp2.getResult(), StringUtils.EMPTY); + Assert.assertEquals(createResp2.getErrorCode().intValue(), + ErrorCode.CREDENTIAL_EVIDENCE_ALREADY_EXISTS.getCode()); + credential.setId(UUID.randomUUID().toString()); + ResponseData addResp1 = evidenceService.addLogByHash(credential.getHash(), "a", + tempCreateWeIdResultWithSetAttr.getUserWeIdPrivateKey()); + Assert.assertEquals(addResp1.getResult(), false); + Assert.assertEquals(addResp1.getErrorCode().intValue(), + ErrorCode.CREDENTIAL_EVIDENCE_NOT_EXIST.getCode()); + ResponseData addResp2 = evidenceService.addSignatureAndLogByHash( + credential.getHash(), "a", tempCreateWeIdResultWithSetAttr.getUserWeIdPrivateKey()); + Assert.assertEquals(addResp2.getResult(), false); + Assert.assertEquals(addResp2.getErrorCode().intValue(), + ErrorCode.CREDENTIAL_EVIDENCE_NOT_EXIST.getCode()); + } + @Test public void testCreateEvidence_MultipleSigners() { CreateWeIdDataResult tempCreateWeIdResultWithSetAttr = @@ -163,19 +198,19 @@ public void testCreateEvidence_MultipleSigners() { CredentialPojo credential = createCredentialPojo(createCredentialPojoArgs); credential.setId(UUID.randomUUID().toString()); String hash = evidenceService.generateHash(credential).getResult().getHash(); - evidenceService.createEvidence(credential, + ResponseData createResp1 = evidenceService.createEvidence(credential, tempCreateWeIdResultWithSetAttr.getUserWeIdPrivateKey()); - evidenceService.addLogByHash(hash, "1.23", + ResponseData addResp1 = evidenceService.addLogByHash(hash, "1.23", tempCreateWeIdResultWithSetAttr.getUserWeIdPrivateKey()); - evidenceService.addLogByHash(hash, "13.15", + ResponseData addResp2 = evidenceService.addLogByHash(hash, "13.15", tempCreateWeIdResultWithSetAttr.getUserWeIdPrivateKey()); // Another guy signs CreateWeIdDataResult tempCreateWeIdResultWithSetAttr2 = createWeIdWithSetAttr(); - evidenceService.createEvidence(credential, + ResponseData createResp2 = evidenceService.addSignatureAndLogByHash( + credential.getHash(), "", tempCreateWeIdResultWithSetAttr2.getUserWeIdPrivateKey()); + ResponseData addResp3 = evidenceService.addLogByHash(hash, "abc", tempCreateWeIdResultWithSetAttr2.getUserWeIdPrivateKey()); - evidenceService.addLogByHash(hash, "abc", - tempCreateWeIdResultWithSetAttr2.getUserWeIdPrivateKey()); - evidenceService.addLogByHash(hash, "eef", + ResponseData addResp4 = evidenceService.addLogByHash(hash, "eef", tempCreateWeIdResultWithSetAttr2.getUserWeIdPrivateKey()); // Now check ResponseData eviInfo = evidenceService.getEvidence(hash); @@ -224,7 +259,7 @@ public void testCreateEvidence_CustomKeyHappyPath() { evi2.getSignInfo().get(signer).getLogs()); evidenceService.addLogByHash(hash, "Insane", tempCreateWeIdResultWithSetAttr.getUserWeIdPrivateKey()); - evidenceService.addLogByCustomKey(credId, "Difficult", + evidenceService.addLogByCustomKey(null, credId, "Difficult", tempCreateWeIdResultWithSetAttr.getUserWeIdPrivateKey()); evi2 = evidenceService.getEvidenceByCustomKey(credId).getResult(); Assert.assertEquals(evi2.getSignInfo().get(signer).getLogs().size(), 3); @@ -252,35 +287,56 @@ public void testCreateEvidence_CustomKeyMultiSignerMultiTimes() { Assert.assertTrue(!StringUtils.isEmpty(resp.getResult())); log = "X:122.5,Y:94.3"; list.add(log); - resp = evidenceService.createEvidenceWithLogAndCustomKey( - credential, - tempCreateWeIdResultWithSetAttr.getUserWeIdPrivateKey(), + ResponseData addResp = evidenceService.addLogByCustomKey( + null, + credId, log, - credId + tempCreateWeIdResultWithSetAttr.getUserWeIdPrivateKey() ); - Assert.assertTrue(!StringUtils.isEmpty(resp.getResult())); + Assert.assertTrue(addResp.getResult()); log = "X:102.5,Y:99.1"; list.add(log); - resp = evidenceService.createEvidenceWithLogAndCustomKey( - credential, - tempCreateWeIdResultWithSetAttr.getUserWeIdPrivateKey(), + addResp = evidenceService.addLogByCustomKey( + null, + credId, log, - credId + tempCreateWeIdResultWithSetAttr.getUserWeIdPrivateKey() ); - Assert.assertTrue(!StringUtils.isEmpty(resp.getResult())); + Assert.assertTrue(addResp.getResult()); log = "X:0,Y:0"; list.add(log); - ResponseData respBool = evidenceService.addLogByCustomKey(credId, log, + addResp = evidenceService.addLogByHash(credential.getHash(), log, tempCreateWeIdResultWithSetAttr.getUserWeIdPrivateKey()); - Assert.assertTrue(respBool.getResult()); + Assert.assertTrue(addResp.getResult()); CreateWeIdDataResult tempCreateWeIdResultWithSetAttr2 = createWeIdWithSetAttr(); - resp = evidenceService.createEvidenceWithLogAndCustomKey( - credential, - tempCreateWeIdResultWithSetAttr2.getUserWeIdPrivateKey(), + addResp = evidenceService.addLogByCustomKey( + null, + credId, + "Age:11", + tempCreateWeIdResultWithSetAttr2.getUserWeIdPrivateKey() + ); + Assert.assertTrue(addResp.getResult()); + addResp = evidenceService.addSignatureAndLogByCustomKey( + null, + credId, "Age:22", - credId + tempCreateWeIdResultWithSetAttr2.getUserWeIdPrivateKey() ); - Assert.assertTrue(!StringUtils.isEmpty(resp.getResult())); + Assert.assertTrue(addResp.getResult()); + addResp = evidenceService.addSignatureAndLogByCustomKey( + null, + credId, + "Age:33", + tempCreateWeIdResultWithSetAttr2.getUserWeIdPrivateKey() + ); + Assert.assertTrue(addResp.getResult()); + addResp = evidenceService.addLogByCustomKey( + null, + credId, + "Age:44", + tempCreateWeIdResultWithSetAttr2.getUserWeIdPrivateKey() + ); + Assert.assertTrue(addResp.getResult()); ResponseData eviCustomKey = evidenceService.getEvidenceByCustomKey(credId); EvidenceInfo evi = eviCustomKey.getResult(); String signer = tempCreateWeIdResultWithSetAttr.getWeId(); @@ -289,7 +345,7 @@ public void testCreateEvidence_CustomKeyMultiSignerMultiTimes() { Assert.assertEquals(evi.getSignInfo().get(signer).getLogs(), list); String signer2 = tempCreateWeIdResultWithSetAttr2.getWeId(); Assert.assertTrue(evi.getSignInfo().get(signer2).getLogs().contains("Age:22") - && evi.getSignInfo().get(signer2).getLogs().size() == 1); + && evi.getSignInfo().get(signer2).getLogs().size() == 3); } @Test @@ -316,7 +372,7 @@ public void testAddLogsAll() { outputBuffer.append("a"); } log = outputBuffer.toString(); - evidenceService.addLogByCustomKey(credId, log, + evidenceService.addLogByCustomKey(null, credId, log, tempCreateWeIdResultWithSetAttr.getUserWeIdPrivateKey()); evi = evidenceService.getEvidenceByCustomKey(credId).getResult(); Assert.assertNotNull(evi); @@ -325,8 +381,6 @@ public void testAddLogsAll() { @Test public void testBatchCreate() throws Exception { - CreateWeIdDataResult tempCreateWeIdResultWithSetAttr = - super.copyCreateWeId(createWeIdResultWithSetAttr); List hashValues = new ArrayList<>(); List signatures = new ArrayList<>(); List timestamps = new ArrayList<>(); @@ -339,9 +393,7 @@ public void testBatchCreate() throws Exception { credential.setId(UUID.randomUUID().toString()); String hash = credential.getHash(); hashValues.add(credential.getHash()); - signatures.add(new String(DataToolUtils.base64Encode(DataToolUtils - .simpleSignatureSerialization(DataToolUtils.signMessage(hash, privateKey))), - StandardCharsets.UTF_8)); + signatures.add(DataToolUtils.secp256k1Sign(hash, new BigInteger(privateKey))); timestamps.add(System.currentTimeMillis()); signers.add(DataToolUtils.convertPrivateKeyToDefaultWeId(privateKey)); logs.add("test log" + i); @@ -391,10 +443,11 @@ public void testBatchCreate() throws Exception { booleans = resp.getResult(); Assert.assertEquals(booleans.size(), hashValues.size()); result = true; + // All hashes already existed, so all fail. for (int i = 0; i < booleans.size(); i++) { result = result && booleans.get(i).booleanValue(); } - Assert.assertTrue(result); + Assert.assertFalse(result); // Check get String hash0 = hashValues.get(0); @@ -402,17 +455,8 @@ public void testBatchCreate() throws Exception { String key1 = customKeys.get(1); EvidenceInfo evidenceInfo0 = evidenceService.getEvidence(hash0).getResult(); EvidenceInfo evidenceInfo1 = evidenceService.getEvidence(hash1).getResult(); - EvidenceInfo evidenceInfo1k = evidenceService.getEvidenceByCustomKey(key1).getResult(); Assert.assertNotNull(evidenceInfo0); Assert.assertNotNull(evidenceInfo1); - Assert.assertNotNull(evidenceInfo1k); - // ran for 3 times - Assert.assertEquals(evidenceInfo0.getSignInfo() - .get(DataToolUtils.convertPrivateKeyToDefaultWeId(privateKey)).getLogs().size(), 3); - // ran only twice (one set null in between) - Assert.assertEquals(evidenceInfo1.getSignInfo() - .get(DataToolUtils.convertPrivateKeyToDefaultWeId(privateKey)).getLogs().size(), 2); - Assert.assertEquals(evidenceInfo1.getCredentialHash(), evidenceInfo1k.getCredentialHash()); } /** @@ -430,7 +474,8 @@ public void testBatchCreateMultiGroup() { List argList = new ArrayList<>(); argList.add(credential.getHash()); argList.add(new String(DataToolUtils.base64Encode(DataToolUtils - .simpleSignatureSerialization(DataToolUtils.signMessage(hash, privateKey))), + .simpleSignatureSerialization(DataToolUtils.secp256k1SignToSignature( + hash, new BigInteger(privateKey)))), StandardCharsets.UTF_8)); argList.add("test log" + i); argList.add(DateUtils.getNoMillisecondTimeStampString()); @@ -488,6 +533,41 @@ public void testRawCreation() { Assert.assertTrue(eviResp.getResult().getSigners().get(0).equalsIgnoreCase(signer1)); } + /** + * Test status: revoked. + */ + @Test + public void testSetRevokeStatus() { + CreateWeIdDataResult tempCreateWeIdResultWithSetAttr = createWeId(); + CredentialPojo credential = createCredentialPojo(createCredentialPojoArgs); + credential.setId(UUID.randomUUID().toString()); + String hash = evidenceService.generateHash(credential).getResult().getHash(); + ResponseData createResp1 = evidenceService.createEvidence(credential, + tempCreateWeIdResultWithSetAttr.getUserWeIdPrivateKey()); + WeIdAuthentication weIdAuthentication = new WeIdAuthentication(); + weIdAuthentication + .setWeIdPrivateKey(tempCreateWeIdResultWithSetAttr.getUserWeIdPrivateKey()); + ResponseData revokeResp = evidenceService.revoke(credential, weIdAuthentication); + Assert.assertTrue(revokeResp.getResult()); + ResponseData getResp = evidenceService.getEvidence(credential.getHash()); + Assert.assertNotNull(getResp.getResult()); + Assert.assertTrue(getResp.getResult().getSignInfo() + .get(tempCreateWeIdResultWithSetAttr.getWeId()).getRevoked()); + revokeResp = evidenceService.unRevoke(credential, weIdAuthentication); + getResp = evidenceService.getEvidence(credential.getHash()); + Assert.assertFalse(getResp.getResult().getSignInfo() + .get(tempCreateWeIdResultWithSetAttr.getWeId()).getRevoked()); + revokeResp = evidenceService.revoke(credential, weIdAuthentication); + getResp = evidenceService.getEvidence(credential.getHash()); + Assert.assertTrue(getResp.getResult().getSignInfo() + .get(tempCreateWeIdResultWithSetAttr.getWeId()).getRevoked()); + EvidenceInfo evidenceInfo = getResp.getResult(); + Assert.assertFalse(evidenceService.isRevoked( + evidenceInfo, createWeIdResultWithSetAttr.getWeId()).getResult()); + Assert.assertTrue(evidenceService.isRevoked( + evidenceInfo, tempCreateWeIdResultWithSetAttr.getWeId()).getResult()); + } + /** * case3: weIdPrivateKey is null. */ @@ -498,7 +578,7 @@ public void testCreateEvidence_priKeyNull() { LogUtil.info(logger, "createEvidence", response); Assert.assertEquals( - ErrorCode.CREDENTIAL_PRIVATE_KEY_NOT_EXISTS.getCode(), + ErrorCode.WEID_PRIVATEKEY_INVALID.getCode(), response.getErrorCode().intValue()); Assert.assertFalse(!response.getResult().isEmpty()); } @@ -516,7 +596,7 @@ public void testCreateEvidence_privateKeyNull() { .createEvidence(credential, tempCreateWeIdResultWithSetAttr.getUserWeIdPrivateKey()); LogUtil.info(logger, "createEvidence", response); Assert.assertEquals( - ErrorCode.CREDENTIAL_PRIVATE_KEY_NOT_EXISTS.getCode(), + ErrorCode.WEID_PRIVATEKEY_INVALID.getCode(), response.getErrorCode().intValue()); Assert.assertFalse(!response.getResult().isEmpty()); } @@ -534,7 +614,7 @@ public void testCreateEvidenceCase05() { .createEvidence(credential, tempCreateWeIdResultWithSetAttr.getUserWeIdPrivateKey()); LogUtil.info(logger, "createEvidence", response); Assert.assertEquals( - ErrorCode.CREDENTIAL_PRIVATE_KEY_NOT_EXISTS.getCode(), + ErrorCode.WEID_PRIVATEKEY_INVALID.getCode(), response.getErrorCode().intValue()); Assert.assertFalse(!response.getResult().isEmpty()); } @@ -552,7 +632,7 @@ public void testCreateEvidence_priKeyBlank() { .createEvidence(credential, tempCreateWeIdResultWithSetAttr.getUserWeIdPrivateKey()); LogUtil.info(logger, "createEvidence", response); Assert.assertEquals( - ErrorCode.CREDENTIAL_PRIVATE_KEY_NOT_EXISTS.getCode(), + ErrorCode.WEID_PRIVATEKEY_INVALID.getCode(), response.getErrorCode().intValue()); Assert.assertFalse(!response.getResult().isEmpty()); } diff --git a/src/test/java/com/webank/weid/full/evidence/TestGetEvidence.java b/src/test/java/com/webank/weid/full/evidence/TestGetEvidence.java index 0d8a56f30..7115121f5 100644 --- a/src/test/java/com/webank/weid/full/evidence/TestGetEvidence.java +++ b/src/test/java/com/webank/weid/full/evidence/TestGetEvidence.java @@ -38,17 +38,10 @@ public class TestGetEvidence extends TestBaseService { private static final Logger logger = LoggerFactory.getLogger(TestGetEvidence.class); - private static String evidenceAddress; @Override public synchronized void testInit() { super.testInit(); - HashString str = new HashString( - DataToolUtils.sha3(DateUtils.getNoMillisecondTimeStampString())); - ResponseData evidence = evidenceService - .createEvidence(str, createWeIdResultWithSetAttr.getUserWeIdPrivateKey()); - Assert.assertTrue(!evidence.getResult().isEmpty()); - evidenceAddress = evidence.getResult(); } /** @@ -56,6 +49,12 @@ public synchronized void testInit() { */ @Test public void testGetEvidence_success() { + HashString str = new HashString( + DataToolUtils.sha3(DateUtils.getNoMillisecondTimeStampString())); + ResponseData evidence = evidenceService + .createEvidence(str, createWeIdResultWithSetAttr.getUserWeIdPrivateKey()); + Assert.assertTrue(!evidence.getResult().isEmpty()); + String evidenceAddress = evidence.getResult(); ResponseData responseData = evidenceService .getEvidence(evidenceAddress); logger.info("testGetEvidenceCase1 result :" + responseData); 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 25974a4fb..8219b38fe 100644 --- a/src/test/java/com/webank/weid/full/weid/TestCreateWeId1.java +++ b/src/test/java/com/webank/weid/full/weid/TestCreateWeId1.java @@ -23,8 +23,8 @@ import mockit.Mock; import mockit.MockUp; -import org.bcos.web3j.crypto.ECKeyPair; -import org.bcos.web3j.crypto.Keys; +import org.fisco.bcos.web3j.crypto.ECKeyPair; +import org.fisco.bcos.web3j.crypto.Keys; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; diff --git a/src/test/java/com/webank/weid/util/TestCrypt.java b/src/test/java/com/webank/weid/util/TestCrypt.java index 3b4b1ba56..3a4abde1a 100644 --- a/src/test/java/com/webank/weid/util/TestCrypt.java +++ b/src/test/java/com/webank/weid/util/TestCrypt.java @@ -19,8 +19,8 @@ package com.webank.weid.util; -import org.bcos.web3j.crypto.ECKeyPair; -import org.bcos.web3j.crypto.Keys; +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; diff --git a/src/test/java/com/webank/weid/util/TestDataTypetUtils.java b/src/test/java/com/webank/weid/util/TestDataTypetUtils.java index c95d4e428..3ddaf8253 100644 --- a/src/test/java/com/webank/weid/util/TestDataTypetUtils.java +++ b/src/test/java/com/webank/weid/util/TestDataTypetUtils.java @@ -24,13 +24,13 @@ import java.util.List; import java.util.UUID; -import org.bcos.web3j.abi.datatypes.DynamicArray; -import org.bcos.web3j.abi.datatypes.DynamicBytes; -import org.bcos.web3j.abi.datatypes.StaticArray; -import org.bcos.web3j.abi.datatypes.generated.Bytes32; -import org.bcos.web3j.abi.datatypes.generated.Int256; -import org.bcos.web3j.abi.datatypes.generated.Uint256; -import org.bcos.web3j.abi.datatypes.generated.Uint8; +import org.fisco.bcos.web3j.abi.datatypes.DynamicArray; +import org.fisco.bcos.web3j.abi.datatypes.DynamicBytes; +import org.fisco.bcos.web3j.abi.datatypes.StaticArray; +import org.fisco.bcos.web3j.abi.datatypes.generated.Bytes32; +import org.fisco.bcos.web3j.abi.datatypes.generated.Int256; +import org.fisco.bcos.web3j.abi.datatypes.generated.Uint256; +import org.fisco.bcos.web3j.abi.datatypes.generated.Uint8; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; diff --git a/src/test/java/com/webank/weid/util/TestDateUtils.java b/src/test/java/com/webank/weid/util/TestDateUtils.java index 04f07b78c..b48bcc772 100644 --- a/src/test/java/com/webank/weid/util/TestDateUtils.java +++ b/src/test/java/com/webank/weid/util/TestDateUtils.java @@ -25,7 +25,7 @@ import java.util.Date; import java.util.TimeZone; -import org.bcos.web3j.abi.datatypes.generated.Int256; +import org.fisco.bcos.web3j.abi.datatypes.generated.Int256; import org.junit.Assert; import org.junit.Before; import org.junit.Test; diff --git a/src/test/java/com/webank/weid/util/TestSignatureUtils.java b/src/test/java/com/webank/weid/util/TestSignatureUtils.java index 8367fff61..4a3ed5b5a 100644 --- a/src/test/java/com/webank/weid/util/TestSignatureUtils.java +++ b/src/test/java/com/webank/weid/util/TestSignatureUtils.java @@ -20,11 +20,10 @@ package com.webank.weid.util; import java.math.BigInteger; -import java.security.SignatureException; import com.lambdaworks.codec.Base64; -import org.bcos.web3j.crypto.ECKeyPair; -import org.bcos.web3j.crypto.Sign; +import org.fisco.bcos.web3j.crypto.ECKeyPair; +import org.fisco.bcos.web3j.crypto.Sign; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; @@ -43,28 +42,18 @@ public class TestSignatureUtils { public void testSignatureUtils() throws Exception { - ECKeyPair keyPair = DataToolUtils.createKeyPair(); - String str = "hello world...........................yes"; - Sign.SignatureData sigData = DataToolUtils.signMessage(str, keyPair); - BigInteger publicKey = DataToolUtils.signatureToPublicKey(str, sigData); - logger.info("publicKey:{} ", publicKey); - String privateKey = "58317564669857453586637110679746575832914889677346283755719850144028639639651"; - Sign.SignatureData sigData2 = DataToolUtils.signMessage(str, privateKey); - publicKey = DataToolUtils.signatureToPublicKey(str, sigData2); - logger.info("publicKey:{} ", publicKey); - - boolean result = DataToolUtils.verifySignature(str, sigData2, publicKey); - Assert.assertTrue(result); - - publicKey = DataToolUtils.publicKeyFromPrivate(new BigInteger(privateKey)); + BigInteger publicKey = DataToolUtils.publicKeyFromPrivate(new BigInteger(privateKey)); logger.info("publicKey:{} ", publicKey); + ECKeyPair keyPair = DataToolUtils.createKeyPair(); keyPair = DataToolUtils.createKeyPairFromPrivate(new BigInteger(privateKey)); logger.info("publicKey:{} ", keyPair.getPublicKey()); logger.info("privateKey:{}", keyPair.getPrivateKey()); + String str = "hello world...........................yes"; + Sign.SignatureData sigData = DataToolUtils.secp256k1SignToSignature(str, keyPair); byte[] serialized = DataToolUtils.simpleSignatureSerialization(sigData); Sign.SignatureData newSigData = DataToolUtils.simpleSignatureDeserialization(serialized); logger.info(newSigData.toString()); diff --git a/src/test/java/com/webank/weid/util/TestTransactionUtils.java b/src/test/java/com/webank/weid/util/TestTransactionUtils.java index 405b82178..12daa2ac7 100644 --- a/src/test/java/com/webank/weid/util/TestTransactionUtils.java +++ b/src/test/java/com/webank/weid/util/TestTransactionUtils.java @@ -25,11 +25,11 @@ import java.util.Map; import org.apache.commons.lang3.StringUtils; -import org.bcos.web3j.abi.datatypes.StaticArray; -import org.bcos.web3j.abi.datatypes.Type; -import org.bcos.web3j.abi.datatypes.generated.Bytes32; -import org.bcos.web3j.abi.datatypes.generated.Int256; -import org.bcos.web3j.protocol.core.methods.response.TransactionReceipt; +import org.fisco.bcos.web3j.abi.datatypes.StaticArray; +import org.fisco.bcos.web3j.abi.datatypes.Type; +import org.fisco.bcos.web3j.abi.datatypes.generated.Bytes32; +import org.fisco.bcos.web3j.abi.datatypes.generated.Int256; +import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt; import org.junit.Assert; import org.junit.Test; @@ -97,11 +97,5 @@ public void testBuildParams() throws Exception { TransactionInfo info = new TransactionInfo(receipt); Assert.assertNotNull(info); Assert.assertNull(new TransactionInfo((TransactionReceipt) null).getBlockNumber()); - Assert.assertNull(TransactionUtils.getTransaction(null)); - } - - @Test - public void testNullTransaction() throws Exception { - Assert.assertNull(TransactionUtils.sendTransaction(null, StringUtils.EMPTY)); } }