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