From 43f2b6c849fc5a5b92a0c8ed25cd7bbfc4bcb10d Mon Sep 17 00:00:00 2001
From: yg36305356 <125480926@qq.com>
Date: Wed, 16 Sep 2020 10:45:12 +0800
Subject: [PATCH 1/6] * remove 1.3 code
---
build.gradle | 2 +-
.../weid/contract/deploy/DeployContract.java | 3 +-
.../contract/deploy/v1/DeployContractV1.java | 430 -------------
.../weid/protocol/amop/GetTransDataArgs.java | 1 -
.../weid/protocol/base/EndpointInfo.java | 1 -
.../weid/protocol/response/RsvSignature.java | 4 +-
.../protocol/response/TransactionInfo.java | 16 +-
.../weid/rpc/callback/OnNotifyCallbackV1.java | 89 ---
.../webank/weid/service/fisco/WeServer.java | 9 +-
.../weid/service/fisco/v1/WeServerV1.java | 203 ------
.../weid/service/fisco/v2/WeServerV2.java | 1 -
.../weid/service/impl/CptServiceImpl.java | 7 +-
.../impl/CredentialPojoServiceImpl.java | 25 +-
.../service/impl/CredentialServiceImpl.java | 24 +-
.../service/impl/EvidenceServiceImpl.java | 41 +-
.../weid/service/impl/WeIdServiceImpl.java | 4 +-
.../impl/callback/KeyManagerCallback.java | 18 +-
.../RequestVerifyChallengeCallback.java | 12 +-
.../service/impl/engine/EngineFactory.java | 30 -
.../fiscov1/AuthorityIssuerEngineV1.java | 533 ----------------
.../engine/fiscov1/CptServiceEngineV1.java | 580 -----------------
.../fiscov1/EvidenceServiceEngineV1.java | 415 ------------
.../RawTransactionServiceEngineV1.java | 252 --------
.../engine/fiscov1/WeIdServiceEngineV1.java | 589 ------------------
.../fiscov2/AuthorityIssuerEngineV2.java | 1 -
.../engine/fiscov2/CptServiceEngineV2.java | 2 +-
.../fiscov2/DataBucketServiceEngineV2.java | 2 +-
.../fiscov2/EvidenceServiceEngineV2.java | 2 -
.../impl/inner/DownTransDataService.java | 16 +-
.../suite/api/crypto/params/KeyGenerator.java | 2 +-
.../weid/suite/auth/impl/WeIdAuthImpl.java | 26 +-
.../weid/suite/crypto/EciesCryptoService.java | 2 +-
.../pdf/impl/PdfTransportationImpl.java | 3 +-
.../com/webank/weid/util/CredentialUtils.java | 3 +-
.../com/webank/weid/util/DataToolUtils.java | 257 ++------
.../java/com/webank/weid/util/DateUtils.java | 2 +-
.../webank/weid/util/TransactionUtils.java | 212 +------
.../java/com/webank/weid/util/WeIdUtils.java | 16 +-
.../com/webank/weid/full/TestBaseUtil.java | 4 +-
.../full/credential/TestCreateCredential.java | 4 +-
.../full/credential/TestVerifyCredential.java | 12 +-
...stVerifyCredentialWithSpecifiedPubKey.java | 2 +-
.../TestVerifyCredentialByIssuer.java | 11 +-
.../TestVerifyCredentialByPublicKey.java | 4 +-
.../full/evidence/TestCreateEvidence.java | 9 +-
.../weid/full/weid/TestCreateWeId1.java | 4 +-
.../java/com/webank/weid/util/TestCrypt.java | 4 +-
.../webank/weid/util/TestDataTypetUtils.java | 14 +-
.../com/webank/weid/util/TestDateUtils.java | 2 +-
.../webank/weid/util/TestSignatureUtils.java | 23 +-
.../weid/util/TestTransactionUtils.java | 16 +-
51 files changed, 155 insertions(+), 3789 deletions(-)
delete mode 100644 src/main/java/com/webank/weid/contract/deploy/v1/DeployContractV1.java
delete mode 100644 src/main/java/com/webank/weid/rpc/callback/OnNotifyCallbackV1.java
delete mode 100644 src/main/java/com/webank/weid/service/fisco/v1/WeServerV1.java
delete mode 100644 src/main/java/com/webank/weid/service/impl/engine/fiscov1/AuthorityIssuerEngineV1.java
delete mode 100644 src/main/java/com/webank/weid/service/impl/engine/fiscov1/CptServiceEngineV1.java
delete mode 100644 src/main/java/com/webank/weid/service/impl/engine/fiscov1/EvidenceServiceEngineV1.java
delete mode 100644 src/main/java/com/webank/weid/service/impl/engine/fiscov1/RawTransactionServiceEngineV1.java
delete mode 100644 src/main/java/com/webank/weid/service/impl/engine/fiscov1/WeIdServiceEngineV1.java
diff --git a/build.gradle b/build.gradle
index a0428c0a..9069594e 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-rc.4-SNAPSHOT") {
exclude group: "org.slf4j", module: "slf4j-log4j12"
}
compile fileTree(dir: 'lib', include: '*.jar')
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 b66d2570..9db6859c 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 90e56861..00000000
--- 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/protocol/amop/GetTransDataArgs.java b/src/main/java/com/webank/weid/protocol/amop/GetTransDataArgs.java
index 7f8f69e7..bd533ea9 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/EndpointInfo.java b/src/main/java/com/webank/weid/protocol/base/EndpointInfo.java
index 1ca66424..b860286d 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/response/RsvSignature.java b/src/main/java/com/webank/weid/protocol/response/RsvSignature.java
index af023af6..4b9ca833 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 21d65d84..f6c020ea 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/callback/OnNotifyCallbackV1.java b/src/main/java/com/webank/weid/rpc/callback/OnNotifyCallbackV1.java
deleted file mode 100644
index e6f65877..00000000
--- 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 d8427fdb..403b2476 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 dd63aa90..00000000
--- 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 0bca4aba..68bd0990 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 09e3fcdc..0ecbc6a1 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;
@@ -302,8 +303,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);
}
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 7535bc8b..40dae797 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 4a1e5170..cae6fb34 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 77e59246..46040a5d 100644
--- a/src/main/java/com/webank/weid/service/impl/EvidenceServiceImpl.java
+++ b/src/main/java/com/webank/weid/service/impl/EvidenceServiceImpl.java
@@ -28,7 +28,7 @@
import com.google.common.base.Charsets;
import com.google.common.io.Files;
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;
@@ -366,33 +366,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 +460,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) {
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 b987eb3d..381bbbd1 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;
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 a6b77144..c427e0f2 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 868a3d1d..5cf8e055 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/EngineFactory.java b/src/main/java/com/webank/weid/service/impl/engine/EngineFactory.java
index 3ebc1b0d..3a8c8e0d 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/fiscov1/AuthorityIssuerEngineV1.java b/src/main/java/com/webank/weid/service/impl/engine/fiscov1/AuthorityIssuerEngineV1.java
deleted file mode 100644
index 20ceab2b..00000000
--- 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
deleted file mode 100644
index 4b807f6b..00000000
--- a/src/main/java/com/webank/weid/service/impl/engine/fiscov1/CptServiceEngineV1.java
+++ /dev/null
@@ -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 96075503..00000000
--- 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 bcba3153..00000000
--- a/src/main/java/com/webank/weid/service/impl/engine/fiscov1/RawTransactionServiceEngineV1.java
+++ /dev/null
@@ -1,252 +0,0 @@
-/*
- * Copyright© (2018-2019) WeBank Co., Ltd.
- *
- * This file is part of weid-java-sdk.
- *
- * weid-java-sdk is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * weid-java-sdk is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with weid-java-sdk. If not, see .
- */
-
-package com.webank.weid.service.impl.engine.fiscov1;
-
-import java.util.List;
-import java.util.Optional;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.commons.collections4.CollectionUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.bcos.web3j.protocol.Web3j;
-import org.bcos.web3j.protocol.core.methods.response.EthGetTransactionReceipt;
-import org.bcos.web3j.protocol.core.methods.response.EthSendTransaction;
-import org.bcos.web3j.protocol.core.methods.response.TransactionReceipt;
-import org.bcos.web3j.protocol.exceptions.TransactionTimeoutException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.webank.weid.constant.ErrorCode;
-import com.webank.weid.constant.WeIdConstant;
-import com.webank.weid.contract.v1.AuthorityIssuerController;
-import com.webank.weid.contract.v1.AuthorityIssuerController.AuthorityIssuerRetLogEventResponse;
-import com.webank.weid.contract.v1.CptController;
-import com.webank.weid.contract.v1.CptController.RegisterCptRetLogEventResponse;
-import com.webank.weid.contract.v1.WeIdContract;
-import com.webank.weid.contract.v1.WeIdContract.WeIdAttributeChangedEventResponse;
-import com.webank.weid.protocol.base.CptBaseInfo;
-import com.webank.weid.protocol.response.ResponseData;
-import com.webank.weid.service.impl.RawTransactionServiceImpl;
-import com.webank.weid.service.impl.engine.BaseEngine;
-import com.webank.weid.service.impl.engine.RawTransactionServiceEngine;
-import com.webank.weid.util.DataToolUtils;
-import com.webank.weid.util.TransactionUtils;
-
-/**
- * awTransactionService runs on FISCO BCOS 1.3.x.
- *
- * @author tonychen 2019年6月26日
- */
-public class RawTransactionServiceEngineV1 extends BaseEngine implements
- RawTransactionServiceEngine {
-
- private static final Logger logger = LoggerFactory.getLogger(RawTransactionServiceImpl.class);
-
- /**
- * 此方法不需要加载合约对象.
- */
- public void reload() {
- logger.info("[reload] nothing to do for reload.");
- }
-
-
- /**
- * Verify Authority Issuer related events.
- *
- * @param event the Event
- * @param opcode the Opcode
- * @return the ErrorCode
- */
- public static ErrorCode verifyAuthorityIssuerRelatedEvent(
- AuthorityIssuerRetLogEventResponse event,
- Integer opcode) {
- if (event == null) {
- return ErrorCode.ILLEGAL_INPUT;
- }
- if (event.addr == null || event.operation == null || event.retCode == null) {
- return ErrorCode.ILLEGAL_INPUT;
- }
- Integer eventOpcode = event.operation.getValue().intValue();
- if (eventOpcode.equals(opcode)) {
- Integer eventRetCode = event.retCode.getValue().intValue();
- return ErrorCode.getTypeByErrorCode(eventRetCode);
- } else {
- return ErrorCode.AUTHORITY_ISSUER_OPCODE_MISMATCH;
- }
- }
-
- /**
- * Send a transaction to blockchain through web3j instance using the transactionHex value.
- *
- * @param transactionHex the transactionHex value
- * @return the transactionReceipt
- * @throws Exception the exception
- */
- public static TransactionReceipt sendTransaction(String transactionHex)
- throws Exception {
- Web3j web3j = (Web3j) getWeb3j();
- EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(transactionHex)
- .sendAsync().get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS);
- if (ethSendTransaction.hasError()) {
- logger.error("Error processing transaction request: "
- + ethSendTransaction.getError().getMessage());
- return null;
- }
- Optional receiptOptional =
- getTransactionReceiptRequest(web3j, ethSendTransaction.getTransactionHash());
- int sumTime = 0;
- try {
- for (int i = 0; i < WeIdConstant.POLL_TRANSACTION_ATTEMPTS; i++) {
- if (!receiptOptional.isPresent()) {
- Thread.sleep((long) WeIdConstant.POLL_TRANSACTION_SLEEP_DURATION);
- sumTime += WeIdConstant.POLL_TRANSACTION_SLEEP_DURATION;
- receiptOptional = getTransactionReceiptRequest(web3j,
- ethSendTransaction.getTransactionHash());
- } else {
- return receiptOptional.get();
- }
- }
- } catch (Exception e) {
- throw new TransactionTimeoutException("Transaction receipt was not generated after "
- + ((sumTime) / 1000
- + " seconds for transaction: " + ethSendTransaction));
- }
- return null;
- }
-
- /**
- * Get a TransactionReceipt request from a transaction Hash.
- *
- * @param web3j the web3j instance to blockchain
- * @param transactionHash the transactionHash value
- * @return the transactionReceipt wrapper
- * @throws Exception the exception
- */
- private static Optional getTransactionReceiptRequest(Web3j web3j,
- String transactionHash) throws Exception {
-
- EthGetTransactionReceipt transactionReceipt =
- web3j.ethGetTransactionReceipt(transactionHash).send();
- if (transactionReceipt.hasError()) {
- logger.error("Error processing transaction request: "
- + transactionReceipt.getError().getMessage());
- return Optional.empty();
- }
- return transactionReceipt.getTransactionReceipt();
- }
-
- /**
- * Verify Register CPT related events.
- *
- * @param transactionReceipt the TransactionReceipt
- * @return the ErrorCode
- */
- public static ResponseData resolveRegisterCptEvents(
- TransactionReceipt transactionReceipt) {
-
- List event = CptController.getRegisterCptRetLogEvents(
- transactionReceipt
- );
-
- if (CollectionUtils.isEmpty(event)) {
- logger.error("[registerCpt] event is empty");
- return new ResponseData<>(null, ErrorCode.CPT_EVENT_LOG_NULL);
- }
-
- return TransactionUtils.getResultByResolveEvent(
- event.get(0).retCode,
- event.get(0).cptId,
- event.get(0).cptVersion,
- transactionReceipt
- );
- }
-
- /**
- * Create a WeIdentity DID from the provided public key, with preset transaction hex value.
- *
- * @param transactionHex the transaction hex value
- * @return Error message if any
- */
- @Override
- public ResponseData createWeId(String transactionHex) {
-
- try {
- TransactionReceipt transactionReceipt = sendTransaction(transactionHex);
- List response =
- WeIdContract.getWeIdAttributeChangedEvents(transactionReceipt);
- if (!CollectionUtils.isEmpty(response)) {
- return new ResponseData<>(Boolean.TRUE.toString(), ErrorCode.SUCCESS);
- }
- } catch (Exception e) {
- logger.error("[createWeId] create failed due to unknown transaction error. ", e);
- }
- return new ResponseData<>(StringUtils.EMPTY, ErrorCode.TRANSACTION_EXECUTE_ERROR);
- }
-
- /**
- * Register a new Authority Issuer on Chain with preset transaction hex value. The inputParam is
- * a Json String, with two keys: WeIdentity DID and Name. Parameters will be ordered as
- * mentioned after validity check; then transactionHex will be sent to blockchain.
- *
- * @param transactionHex the transaction hex value
- * @return true if succeeds, false otherwise
- */
- @Override
- public ResponseData registerAuthorityIssuer(String transactionHex) {
-
- try {
- TransactionReceipt transactionReceipt = sendTransaction(transactionHex);
-
- List eventList =
- AuthorityIssuerController.getAuthorityIssuerRetLogEvents(transactionReceipt);
- AuthorityIssuerRetLogEventResponse event = eventList.get(0);
- ErrorCode errorCode = verifyAuthorityIssuerRelatedEvent(event,
- WeIdConstant.ADD_AUTHORITY_ISSUER_OPCODE);
- Boolean result = errorCode.getCode() == ErrorCode.SUCCESS.getCode();
- return new ResponseData<>(result.toString(), errorCode);
- } catch (Exception e) {
- logger.error("[registerAuthorityIssuer] register failed due to transaction error.", e);
- }
- return new ResponseData<>(StringUtils.EMPTY, ErrorCode.TRANSACTION_EXECUTE_ERROR);
- }
-
- /**
- * Register a new CPT to the blockchain with preset transaction hex value.
- *
- * @param transactionHex the transaction hex value
- * @return The registered CPT info
- */
- public ResponseData registerCpt(String transactionHex) {
-
- try {
- TransactionReceipt transactionReceipt = sendTransaction(transactionHex);
- CptBaseInfo cptBaseInfo = resolveRegisterCptEvents(transactionReceipt)
- .getResult();
-
- if (cptBaseInfo != null) {
- return new ResponseData<>(DataToolUtils.objToJsonStrWithNoPretty(cptBaseInfo),
- ErrorCode.SUCCESS);
- }
- } catch (Exception e) {
- logger.error("[registerCpt] register failed due to unknown transaction error. ", e);
- }
- return new ResponseData<>(StringUtils.EMPTY, ErrorCode.TRANSACTION_EXECUTE_ERROR);
- }
-}
diff --git a/src/main/java/com/webank/weid/service/impl/engine/fiscov1/WeIdServiceEngineV1.java b/src/main/java/com/webank/weid/service/impl/engine/fiscov1/WeIdServiceEngineV1.java
deleted file mode 100644
index 017ee811..00000000
--- a/src/main/java/com/webank/weid/service/impl/engine/fiscov1/WeIdServiceEngineV1.java
+++ /dev/null
@@ -1,589 +0,0 @@
-/*
- * Copyright© (2018-2019) WeBank Co., Ltd.
- *
- * This file is part of weid-java-sdk.
- *
- * weid-java-sdk is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * weid-java-sdk is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with weid-java-sdk. If not, see .
- */
-
-package com.webank.weid.service.impl.engine.fiscov1;
-
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.stream.Collectors;
-
-import org.apache.commons.collections4.CollectionUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.bcos.web3j.abi.EventEncoder;
-import org.bcos.web3j.abi.TypeReference;
-import org.bcos.web3j.abi.datatypes.Address;
-import org.bcos.web3j.abi.datatypes.Bool;
-import org.bcos.web3j.abi.datatypes.DynamicBytes;
-import org.bcos.web3j.abi.datatypes.Event;
-import org.bcos.web3j.abi.datatypes.generated.Bytes32;
-import org.bcos.web3j.abi.datatypes.generated.Int256;
-import org.bcos.web3j.abi.datatypes.generated.Uint256;
-import org.bcos.web3j.protocol.Web3j;
-import org.bcos.web3j.protocol.core.DefaultBlockParameterNumber;
-import org.bcos.web3j.protocol.core.methods.response.EthBlock;
-import org.bcos.web3j.protocol.core.methods.response.EthGetTransactionReceipt;
-import org.bcos.web3j.protocol.core.methods.response.Log;
-import org.bcos.web3j.protocol.core.methods.response.Transaction;
-import org.bcos.web3j.protocol.core.methods.response.TransactionReceipt;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.webank.weid.constant.ErrorCode;
-import com.webank.weid.constant.ResolveEventLogStatus;
-import com.webank.weid.constant.WeIdConstant;
-import com.webank.weid.contract.v1.WeIdContract;
-import com.webank.weid.contract.v1.WeIdContract.WeIdAttributeChangedEventResponse;
-import com.webank.weid.exception.DataTypeCastException;
-import com.webank.weid.exception.ResolveAttributeException;
-import com.webank.weid.protocol.base.AuthenticationProperty;
-import com.webank.weid.protocol.base.PublicKeyProperty;
-import com.webank.weid.protocol.base.ServiceProperty;
-import com.webank.weid.protocol.base.WeIdDocument;
-import com.webank.weid.protocol.base.WeIdPojo;
-import com.webank.weid.protocol.response.ResolveEventLogResult;
-import com.webank.weid.protocol.response.ResponseData;
-import com.webank.weid.protocol.response.TransactionInfo;
-import com.webank.weid.service.impl.engine.BaseEngine;
-import com.webank.weid.service.impl.engine.WeIdServiceEngine;
-import com.webank.weid.util.DataToolUtils;
-import com.webank.weid.util.DateUtils;
-import com.webank.weid.util.WeIdUtils;
-
-/**
- * WeIdServiceEngine calls the weid contract which runs on FISCO BCOS 1.3.x version.
- *
- * @author tonychen 2019年6月21日
- */
-public class WeIdServiceEngineV1 extends BaseEngine implements WeIdServiceEngine {
-
- /**
- * Block number for stopping parsing.
- */
- private static final int STOP_RESOLVE_BLOCK_NUMBER = 0;
- /**
- * WeIdentity DID contract address.
- */
-
- private static final Logger logger = LoggerFactory.getLogger(WeIdServiceEngineV1.class);
- /**
- * The topic map.
- */
- private static final HashMap topicMap;
- /**
- * WeIdentity DID contract object, for calling weIdentity DID contract.
- */
- private static WeIdContract weIdContract;
-
- static {
- // initialize the event topic
- topicMap = new HashMap();
- final Event event =
- new Event(
- WeIdConstant.WEID_EVENT_ATTRIBUTE_CHANGE,
- Arrays.>asList(new TypeReference() {
- }),
- Arrays.>asList(
- new TypeReference() {
- },
- new TypeReference() {
- },
- new TypeReference() {
- },
- new TypeReference() {
- })
- );
- topicMap.put(
- EventEncoder.encode(event),
- WeIdConstant.WEID_EVENT_ATTRIBUTE_CHANGE
- );
- }
-
- /**
- * 构造函数.
- */
- public WeIdServiceEngineV1() {
- if (weIdContract == null) {
- reload();
- }
- }
-
- private static ResolveEventLogResult resolveAttributeEvent(
- String weId,
- TransactionReceipt receipt,
- WeIdDocument result) {
-
- List eventlog =
- WeIdContract.getWeIdAttributeChangedEvents(receipt);
- ResolveEventLogResult response = new ResolveEventLogResult();
-
- if (CollectionUtils.isEmpty(eventlog)) {
- response.setResolveEventLogStatus(ResolveEventLogStatus.STATUS_EVENTLOG_NULL);
- return response;
- }
-
- int previousBlock = 0;
- for (WeIdAttributeChangedEventResponse res : eventlog) {
- if (res.identity == null || res.updated == null || res.previousBlock == null) {
- response.setResolveEventLogStatus(ResolveEventLogStatus.STATUS_RES_NULL);
- return response;
- }
-
- String identity = res.identity.toString();
- if (result.getUpdated() == null) {
- long timeStamp = res.updated.getValue().longValue();
- result.setUpdated(timeStamp);
- }
- String weAddress = WeIdUtils.convertWeIdToAddress(weId);
- if (!StringUtils.equals(weAddress, identity)) {
- response.setResolveEventLogStatus(ResolveEventLogStatus.STATUS_KEY_NOT_MATCH);
- return response;
- }
-
- String key = DataToolUtils.bytes32ToString(res.key);
- String value = DataToolUtils.dynamicBytesToString(res.value);
- previousBlock = res.previousBlock.getValue().intValue();
- buildupWeIdAttribute(key, value, weId, result);
- }
-
- response.setPreviousBlock(previousBlock);
- response.setResolveEventLogStatus(ResolveEventLogStatus.STATUS_SUCCESS);
- return response;
- }
-
- private static void buildupWeIdAttribute(
- String key, String value, String weId, WeIdDocument result) {
- if (StringUtils.startsWith(key, WeIdConstant.WEID_DOC_PUBLICKEY_PREFIX)) {
- buildWeIdPublicKeys(value, weId, result);
- } else if (StringUtils.startsWith(key, WeIdConstant.WEID_DOC_AUTHENTICATE_PREFIX)) {
- buildWeIdPublicKeys(value, weId, result);
- buildWeIdAuthentication(value, weId, result);
- } else if (StringUtils.startsWith(key, WeIdConstant.WEID_DOC_SERVICE_PREFIX)) {
- buildWeIdService(key, value, weId, result);
- } else {
- buildWeIdAttributeDefault(key, value, weId, result);
- }
- }
-
- private static void buildWeIdPublicKeys(String value, String weId, WeIdDocument result) {
-
- logger.info("method buildWeIdPublicKeys() parameter::value:{}, weId:{}, "
- + "result:{}", value, weId, result);
- List pubkeyList = result.getPublicKey();
- // Only store the latest public key
- // OBSOLETE and non-OBSOLETE public keys are regarded as the same
- String trimmedPubKey = StringUtils
- .splitByWholeSeparator(value.replace(
- WeIdConstant.REMOVED_PUBKEY_TAG, ""), WeIdConstant.SEPARATOR)[0];
- for (PublicKeyProperty pr : pubkeyList) {
- if (pr.getPublicKey().contains(trimmedPubKey)) {
- return;
- }
- }
- PublicKeyProperty pubKey = new PublicKeyProperty();
- pubKey.setId(
- new StringBuffer()
- .append(weId)
- .append("#keys-")
- .append(result.getPublicKey().size())
- .toString()
- );
- String[] publicKeyData = StringUtils.splitByWholeSeparator(value, WeIdConstant.SEPARATOR);
- if (publicKeyData != null && publicKeyData.length == 2) {
- pubKey.setPublicKey(publicKeyData[0]);
- String weAddress = publicKeyData[1];
- String owner = WeIdUtils.convertAddressToWeId(weAddress);
- pubKey.setOwner(owner);
- }
- result.getPublicKey().add(pubKey);
- }
-
- private static void buildWeIdAuthentication(String value, String weId, WeIdDocument result) {
-
- logger.info("method buildWeIdAuthentication() parameter::value:{}, weId:{}, "
- + "result:{}", value, weId, result);
- AuthenticationProperty auth = new AuthenticationProperty();
- List keys = result.getPublicKey();
- List authList = result.getAuthentication();
-
- // Firstly, if this is an obsolete auth, directly append it and return unless a same
- // one exists; if this is a normal auth, then check whether there is an existing obsolete
- // one. if so, return. if not, go down further.
- if (value.contains(WeIdConstant.REMOVED_AUTHENTICATION_TAG)) {
- for (AuthenticationProperty ap : authList) {
- String pubKeyId = ap.getPublicKey();
- for (PublicKeyProperty pkp : keys) {
- if (pubKeyId.equalsIgnoreCase(pkp.getId()) && value
- .contains(pkp.getPublicKey())) {
- return;
- }
- }
- }
- auth.setPublicKey(value);
- result.getAuthentication().add(auth);
- } else {
- for (AuthenticationProperty ap : authList) {
- if (ap.getPublicKey()
- .replace(WeIdConstant.REMOVED_AUTHENTICATION_TAG, "")
- .contains(value) && ap
- .getPublicKey()
- .contains(WeIdConstant.REMOVED_AUTHENTICATION_TAG)) {
- return;
- }
- }
- }
-
- for (PublicKeyProperty r : keys) {
- if (StringUtils.contains(value, r.getPublicKey())) {
- for (AuthenticationProperty ar : authList) {
- if (StringUtils.equals(ar.getPublicKey(), r.getId())) {
- return;
- }
- }
- auth.setPublicKey(r.getId());
- result.getAuthentication().add(auth);
- }
- }
- }
-
- private static void buildWeIdService(String key, String value, String weId,
- WeIdDocument result) {
-
- logger.info("method buildWeIdService() parameter::key{}, value:{}, weId:{}, "
- + "result:{}", key, value, weId, result);
- String service = StringUtils.splitByWholeSeparator(key, "/")[2];
- List serviceList = result.getService();
- for (ServiceProperty sr : serviceList) {
- if (StringUtils.equals(service, sr.getType())) {
- return;
- }
- }
- ServiceProperty serviceResult = new ServiceProperty();
- serviceResult.setType(service);
- serviceResult.setServiceEndpoint(value);
- result.getService().add(serviceResult);
- }
-
- private static void buildWeIdAttributeDefault(
- String key, String value, String weId, WeIdDocument result) {
-
- logger.info("method buildWeIdAttributeDefault() parameter::key{}, value:{}, weId:{}, "
- + "result:{}", key, value, weId, result);
- switch (key) {
- case WeIdConstant.WEID_DOC_CREATED:
- result.setCreated(Long.valueOf(value));
- break;
- default:
- break;
- }
- }
-
- private static ResolveEventLogResult resolveEventLog(
- String weId, Log log, TransactionReceipt receipt, WeIdDocument result) {
- String topic = log.getTopics().get(0);
- String event = topicMap.get(topic);
-
- if (StringUtils.isNotBlank(event)) {
- switch (event) {
- case WeIdConstant.WEID_EVENT_ATTRIBUTE_CHANGE:
- return resolveAttributeEvent(weId, receipt, result);
- default:
- }
- }
- ResolveEventLogResult response = new ResolveEventLogResult();
- response.setResolveEventLogStatus(ResolveEventLogStatus.STATUS_EVENT_NULL);
- return response;
- }
-
- private static void resolveTransaction(
- String weId,
- int blockNumber,
- WeIdDocument result) {
-
- int previousBlock = blockNumber;
- while (previousBlock != STOP_RESOLVE_BLOCK_NUMBER) {
- int currentBlockNumber = previousBlock;
- EthBlock latestBlock = null;
- try {
- latestBlock =
- ((Web3j) getWeb3j())
- .ethGetBlockByNumber(
- new DefaultBlockParameterNumber(currentBlockNumber),
- true
- )
- .send();
- } catch (IOException e) {
- logger.error(
- "[resolveTransaction]:get block by number :{} failed. Exception message:{}",
- currentBlockNumber,
- e
- );
- }
- if (latestBlock == null) {
- logger.info(
- "[resolveTransaction]:get block by number :{} . latestBlock is null",
- currentBlockNumber
- );
- return;
- }
- List transList =
- latestBlock
- .getBlock()
- .getTransactions()
- .stream()
- .map(transactionResult -> (Transaction) transactionResult.get())
- .collect(Collectors.toList());
-
- previousBlock = 0;
- try {
- for (Transaction transaction : transList) {
- String transHash = transaction.getHash();
-
- EthGetTransactionReceipt rec1 = ((Web3j) getWeb3j())
- .ethGetTransactionReceipt(transHash)
- .send();
- TransactionReceipt receipt = rec1.getTransactionReceipt().get();
- List logs = rec1.getResult().getLogs();
- for (Log log : logs) {
- ResolveEventLogResult returnValue =
- resolveEventLog(weId, log, receipt, result);
- if (returnValue.getResultStatus().equals(
- ResolveEventLogStatus.STATUS_SUCCESS)) {
- if (returnValue.getPreviousBlock() == currentBlockNumber) {
- continue;
- }
- previousBlock = returnValue.getPreviousBlock();
- }
- }
- }
- } catch (IOException | DataTypeCastException e) {
- logger.error(
- "[resolveTransaction]: get TransactionReceipt by weId :{} failed.",
- weId,
- e
- );
- throw new ResolveAttributeException(
- ErrorCode.TRANSACTION_EXECUTE_ERROR.getCode(),
- ErrorCode.TRANSACTION_EXECUTE_ERROR.getCodeDesc());
- }
- }
- }
-
- /**
- * 重新加载静态合约对象.
- */
- public void reload() {
- weIdContract = getContractService(fiscoConfig.getWeIdAddress(), WeIdContract.class);
- }
-
- /* (non-Javadoc)
- * @see com.webank.weid.service.impl.engine.WeIdController#isWeIdExist(java.lang.String)
- */
- @Override
- public ResponseData isWeIdExist(String weId) {
- try {
- Bool isExist = weIdContract
- .isIdentityExist(new Address(WeIdUtils.convertWeIdToAddress(weId)))
- .get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS);
- Boolean result = isExist.getValue();
- return new ResponseData<>(result, ErrorCode.SUCCESS);
- } catch (InterruptedException | ExecutionException e) {
- logger.error("[isWeIdExist] execute failed. Error message :{}", e);
- return new ResponseData<>(false, ErrorCode.TRANSACTION_EXECUTE_ERROR);
- } catch (TimeoutException e) {
- logger.error("[isWeIdExist] execute with timeout. Error message :{}", e);
- return new ResponseData<>(false, ErrorCode.TRANSACTION_TIMEOUT);
- } catch (Exception e) {
- logger.error("[isWeIdExist] execute failed. Error message :{}", e);
- return new ResponseData<>(false, ErrorCode.UNKNOW_ERROR);
- }
- }
-
- /* (non-Javadoc)
- * @see com.webank.weid.service.impl.engine.WeIdController#getWeIdDocument(java.lang.String)
- */
- @Override
- public ResponseData getWeIdDocument(String weId) {
- WeIdDocument result = new WeIdDocument();
- result.setId(weId);
- int latestBlockNumber = 0;
- try {
- String identityAddr = WeIdUtils.convertWeIdToAddress(weId);
- latestBlockNumber =
- weIdContract
- .getLatestRelatedBlock(new Address(identityAddr))
- .get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS)
- .getValue()
- .intValue();
- if (0 == latestBlockNumber) {
- return new ResponseData<>(null, ErrorCode.WEID_DOES_NOT_EXIST);
- }
-
- resolveTransaction(weId, latestBlockNumber, result);
- return new ResponseData<>(result, ErrorCode.SUCCESS);
- } catch (InterruptedException | ExecutionException e) {
- logger.error("Set weId service failed. Error message :{}", e);
- return new ResponseData<>(null, ErrorCode.TRANSACTION_EXECUTE_ERROR);
- } catch (TimeoutException e) {
- logger.error("Set weId service timeout. Error message :{}", e);
- return new ResponseData<>(null, ErrorCode.TRANSACTION_TIMEOUT);
- } catch (ResolveAttributeException e) {
- logger.error("[getWeIdDocument]: resolveTransaction failed. "
- + "weId: {}, errorCode:{}",
- weId,
- e.getErrorCode(),
- e);
- return new ResponseData<>(null, ErrorCode.getTypeByErrorCode(e.getErrorCode()));
- } catch (Exception e) {
- logger.error("[getWeIdDocument]: exception.", e);
- return new ResponseData<>(null, ErrorCode.UNKNOW_ERROR);
- }
- }
-
-
- /* (non-Javadoc)
- * @see com.webank.weid.service.impl.engine.WeIdController
- * #createWeId(java.lang.String, java.lang.String, java.lang.String)
- */
- @Override
-
- public ResponseData createWeId(
- String weAddress,
- String publicKey,
- String privateKey,
- boolean isDelegate) {
-
- WeIdContract weIdContract = (WeIdContract) reloadContract(
- fiscoConfig.getWeIdAddress(),
- privateKey,
- WeIdContract.class);
- try {
- DynamicBytes auth = DataToolUtils.stringToDynamicBytes(
- new StringBuffer()
- .append(publicKey)
- .append(WeIdConstant.SEPARATOR)
- .append(weAddress)
- .toString());
- DynamicBytes created = DataToolUtils
- .stringToDynamicBytes(DateUtils.getNoMillisecondTimeStampString());
-
- Future future = null;
- if (isDelegate) {
- return new ResponseData<>(false, ErrorCode.FISCO_BCOS_VERSION_NOT_SUPPORTED);
- } else {
- future = weIdContract.createWeId(
- new Address(weAddress),
- auth,
- created,
- DateUtils.getNoMillisecondTimeStampInt256()
- );
- }
- TransactionReceipt receipt =
- future.get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS);
- TransactionInfo info = new TransactionInfo(receipt);
- List response =
- WeIdContract.getWeIdAttributeChangedEvents(receipt);
-
- if (CollectionUtils.isEmpty(response)) {
- logger.error(
- "The input private key does not match the current weid, operation of "
- + "modifying weid is not allowed. we address is {}",
- weAddress
- );
- return new ResponseData(false,
- ErrorCode.WEID_PRIVATEKEY_DOES_NOT_MATCH,
- info);
- }
- return new ResponseData(true, ErrorCode.SUCCESS, info);
- } catch (InterruptedException | ExecutionException e) {
- logger.error("Set public key failed. Error message :{}", e);
- return new ResponseData(false, ErrorCode.TRANSACTION_EXECUTE_ERROR);
- } catch (TimeoutException e) {
- logger.error("Set public key timeout. Error message :{}", e);
- return new ResponseData(false, ErrorCode.TRANSACTION_TIMEOUT);
- }
- }
-
-
- /* (non-Javadoc)
- * @see com.webank.weid.service.impl.engine.WeIdController
- * #setAttribute(java.lang.String, java.lang.String, java.lang.String)
- */
- @Override
- public ResponseData setAttribute(
- String weAddress,
- String attributeKey,
- String value,
- String privateKey,
- boolean isDelegate) {
-
- try {
- WeIdContract weIdContract = (WeIdContract) reloadContract(
- fiscoConfig.getWeIdAddress(),
- privateKey,
- WeIdContract.class);
- Future future = null;
- if (isDelegate) {
- return new ResponseData<>(false, ErrorCode.FISCO_BCOS_VERSION_NOT_SUPPORTED);
- } else {
- future =
- weIdContract.setAttribute(
- new Address(weAddress),
- DataToolUtils.stringToBytes32(attributeKey),
- DataToolUtils.stringToDynamicBytes(
- value),
- DateUtils.getNoMillisecondTimeStampInt256()
- );
- }
- TransactionReceipt receipt =
- future.get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS);
- TransactionInfo info = new TransactionInfo(receipt);
- List response =
- WeIdContract.getWeIdAttributeChangedEvents(receipt);
- if (CollectionUtils.isNotEmpty(response)) {
- return new ResponseData(true, ErrorCode.SUCCESS, info);
- } else {
- return new ResponseData(false,
- ErrorCode.WEID_PRIVATEKEY_DOES_NOT_MATCH,
- info);
- }
- } catch (InterruptedException | ExecutionException e) {
- logger.error("Set public key failed. Error message :{}", e);
- return new ResponseData(false, ErrorCode.TRANSACTION_EXECUTE_ERROR);
- } catch (TimeoutException e) {
- logger.error("Set public key timeout. Error message :{}", e);
- return new ResponseData(false, ErrorCode.TRANSACTION_TIMEOUT);
- }
- }
-
- @Override
- public ResponseData> getWeIdList(
- Integer blockNumber,
- Integer pageSize,
- Integer indexInBlock,
- boolean direction
- ) throws Exception {
- return new ResponseData<>(null, ErrorCode.THIS_IS_UNSUPPORTED);
- }
-}
diff --git a/src/main/java/com/webank/weid/service/impl/engine/fiscov2/AuthorityIssuerEngineV2.java b/src/main/java/com/webank/weid/service/impl/engine/fiscov2/AuthorityIssuerEngineV2.java
index 590b194d..abdf0540 100644
--- a/src/main/java/com/webank/weid/service/impl/engine/fiscov2/AuthorityIssuerEngineV2.java
+++ b/src/main/java/com/webank/weid/service/impl/engine/fiscov2/AuthorityIssuerEngineV2.java
@@ -23,7 +23,6 @@
import java.util.ArrayList;
import java.util.List;
-import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.fisco.bcos.web3j.abi.datatypes.Address;
import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt;
diff --git a/src/main/java/com/webank/weid/service/impl/engine/fiscov2/CptServiceEngineV2.java b/src/main/java/com/webank/weid/service/impl/engine/fiscov2/CptServiceEngineV2.java
index 6df32761..bd723c05 100644
--- a/src/main/java/com/webank/weid/service/impl/engine/fiscov2/CptServiceEngineV2.java
+++ b/src/main/java/com/webank/weid/service/impl/engine/fiscov2/CptServiceEngineV2.java
@@ -37,8 +37,8 @@
import com.webank.wedpr.selectivedisclosure.proto.TemplatePublicKey;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
-import org.bcos.web3j.crypto.Sign;
import org.fisco.bcos.web3j.abi.EventEncoder;
+import org.fisco.bcos.web3j.crypto.Sign;
import org.fisco.bcos.web3j.protocol.Web3j;
import org.fisco.bcos.web3j.protocol.core.DefaultBlockParameterNumber;
import org.fisco.bcos.web3j.protocol.core.methods.response.BcosBlock;
diff --git a/src/main/java/com/webank/weid/service/impl/engine/fiscov2/DataBucketServiceEngineV2.java b/src/main/java/com/webank/weid/service/impl/engine/fiscov2/DataBucketServiceEngineV2.java
index f6231193..178f1918 100644
--- a/src/main/java/com/webank/weid/service/impl/engine/fiscov2/DataBucketServiceEngineV2.java
+++ b/src/main/java/com/webank/weid/service/impl/engine/fiscov2/DataBucketServiceEngineV2.java
@@ -5,7 +5,7 @@
import java.util.List;
import org.apache.commons.lang3.StringUtils;
-import org.bcos.web3j.abi.datatypes.generated.Bytes32;
+import org.fisco.bcos.web3j.abi.datatypes.generated.Bytes32;
import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt;
import org.fisco.bcos.web3j.tuples.generated.Tuple2;
import org.fisco.bcos.web3j.tuples.generated.Tuple4;
diff --git a/src/main/java/com/webank/weid/service/impl/engine/fiscov2/EvidenceServiceEngineV2.java b/src/main/java/com/webank/weid/service/impl/engine/fiscov2/EvidenceServiceEngineV2.java
index 23032153..a35b6584 100644
--- a/src/main/java/com/webank/weid/service/impl/engine/fiscov2/EvidenceServiceEngineV2.java
+++ b/src/main/java/com/webank/weid/service/impl/engine/fiscov2/EvidenceServiceEngineV2.java
@@ -19,7 +19,6 @@
package com.webank.weid.service.impl.engine.fiscov2;
-import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
@@ -53,7 +52,6 @@
import com.webank.weid.protocol.response.TransactionInfo;
import com.webank.weid.service.impl.engine.BaseEngine;
import com.webank.weid.service.impl.engine.EvidenceServiceEngine;
-import com.webank.weid.service.impl.inner.PropertiesService;
import com.webank.weid.suite.cache.CacheManager;
import com.webank.weid.suite.cache.CacheNode;
import com.webank.weid.util.DataToolUtils;
diff --git a/src/main/java/com/webank/weid/service/impl/inner/DownTransDataService.java b/src/main/java/com/webank/weid/service/impl/inner/DownTransDataService.java
index 16fb13e5..17b7fb89 100644
--- a/src/main/java/com/webank/weid/service/impl/inner/DownTransDataService.java
+++ b/src/main/java/com/webank/weid/service/impl/inner/DownTransDataService.java
@@ -221,19 +221,11 @@ private boolean checkAuthority(GetTransDataArgs arg, Map keyMap)
null
);
if (errorCode.getCode() != ErrorCode.SUCCESS.getCode()) {
- errorCode = DataToolUtils.verifySignatureFromWeId(
- arg.getResourceId(),
- arg.getSignValue(),
- domRes.getResult(),
- null
+ logger.error(
+ "[checkAuthority] the data is be changed, this weid is {}.",
+ arg.getWeId()
);
- if (errorCode.getCode() != ErrorCode.SUCCESS.getCode()) {
- logger.error(
- "[checkAuthority] the data is be changed, this weid is {}.",
- arg.getWeId()
- );
- return false;
- }
+ return false;
}
logger.info("[checkAuthority] you have the permission to get key.");
return true;
diff --git a/src/main/java/com/webank/weid/suite/api/crypto/params/KeyGenerator.java b/src/main/java/com/webank/weid/suite/api/crypto/params/KeyGenerator.java
index ae90f57c..e1937df0 100644
--- a/src/main/java/com/webank/weid/suite/api/crypto/params/KeyGenerator.java
+++ b/src/main/java/com/webank/weid/suite/api/crypto/params/KeyGenerator.java
@@ -28,8 +28,8 @@
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
-import org.bcos.web3j.utils.Numeric;
import org.fisco.bcos.web3j.crypto.Keys;
+import org.fisco.bcos.web3j.utils.Numeric;
import com.webank.weid.util.DataToolUtils;
diff --git a/src/main/java/com/webank/weid/suite/auth/impl/WeIdAuthImpl.java b/src/main/java/com/webank/weid/suite/auth/impl/WeIdAuthImpl.java
index 27342f25..bf55d5eb 100644
--- a/src/main/java/com/webank/weid/suite/auth/impl/WeIdAuthImpl.java
+++ b/src/main/java/com/webank/weid/suite/auth/impl/WeIdAuthImpl.java
@@ -19,6 +19,7 @@
package com.webank.weid.suite.auth.impl;
+import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -69,7 +70,6 @@ public class WeIdAuthImpl implements WeIdAuth {
* amop service instance.
*/
private static AmopService amopService = new AmopServiceImpl();
- private static Map weIdAuthCache = new HashMap<>();
private static WeIdAuthCallback weIdAuthCallback;
private static WeIdAuthAmopCallback weIdAuthAmopCallback = new WeIdAuthAmopCallback();
private static RequestVerifyChallengeCallback VerifyChallengeCallback =
@@ -167,15 +167,7 @@ public ResponseData createAuthenticatedChannel(
ErrorCode verifyErrorCode = DataToolUtils
.verifySecp256k1SignatureFromWeId(rawData, challengeSignData, weIdDocument, null);
if (verifyErrorCode.getCode() != ErrorCode.SUCCESS.getCode()) {
- verifyErrorCode = DataToolUtils
- .verifySignatureFromWeId(rawData, challengeSignData, weIdDocument, null);
- if (verifyErrorCode.getCode() != ErrorCode.SUCCESS.getCode()) {
- logger.error(
- "[createMutualAuthenticatedChannel] verify challenge signature failed,"
- + " Error code:{}",
- verifyErrorCode.getCode());
- return new ResponseData(null, verifyErrorCode);
- }
+ return new ResponseData(null, verifyErrorCode);
}
return new ResponseData(weIdAuthObj, ErrorCode.SUCCESS);
}
@@ -253,21 +245,13 @@ public ResponseData createMutualAuthenticatedChannel(
ErrorCode verifyErrorCode = DataToolUtils
.verifySecp256k1SignatureFromWeId(rawData, challengeSignData, weIdDocument, null);
if (verifyErrorCode.getCode() != ErrorCode.SUCCESS.getCode()) {
- verifyErrorCode = DataToolUtils
- .verifySignatureFromWeId(rawData, challengeSignData, weIdDocument, null);
- if (verifyErrorCode.getCode() != ErrorCode.SUCCESS.getCode()) {
- logger.error(
- "[createMutualAuthenticatedChannel] verify challenge signature failed, "
- + "Error code:{}",
- verifyErrorCode.getCode());
- return new ResponseData(null, verifyErrorCode);
- }
+ return new ResponseData(null, verifyErrorCode);
}
//双向auth,发起方也需要对对手方的challenge进行签名
String challenge1 = (String) dataMap.get(ParamKeyConstant.WEID_AUTH_CHALLENGE);
- String signData = DataToolUtils
- .sign(challenge1, weIdAuthentication.getWeIdPrivateKey().getPrivateKey());
+ String signData = DataToolUtils.secp256k1Sign(
+ challenge1, new BigInteger(weIdAuthentication.getWeIdPrivateKey().getPrivateKey()));
RequestVerifyChallengeArgs verifyChallengeArgs = new RequestVerifyChallengeArgs();
verifyChallengeArgs.setSignData(signData);
verifyChallengeArgs.setChallenge(Challenge.fromJson(challenge1));
diff --git a/src/main/java/com/webank/weid/suite/crypto/EciesCryptoService.java b/src/main/java/com/webank/weid/suite/crypto/EciesCryptoService.java
index 15f0aa8c..07148d82 100644
--- a/src/main/java/com/webank/weid/suite/crypto/EciesCryptoService.java
+++ b/src/main/java/com/webank/weid/suite/crypto/EciesCryptoService.java
@@ -28,8 +28,8 @@
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
-import org.bcos.web3j.utils.Numeric;
import org.fisco.bcos.web3j.crypto.Keys;
+import org.fisco.bcos.web3j.utils.Numeric;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
diff --git a/src/main/java/com/webank/weid/suite/transportation/pdf/impl/PdfTransportationImpl.java b/src/main/java/com/webank/weid/suite/transportation/pdf/impl/PdfTransportationImpl.java
index 0c3983e6..311fab58 100644
--- a/src/main/java/com/webank/weid/suite/transportation/pdf/impl/PdfTransportationImpl.java
+++ b/src/main/java/com/webank/weid/suite/transportation/pdf/impl/PdfTransportationImpl.java
@@ -48,6 +48,7 @@
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.fisco.bcos.web3j.crypto.SHA3Digest;
+import org.fisco.bcos.web3j.utils.Numeric;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -1314,7 +1315,7 @@ private String getChecksum(byte[] pdfFileByte) {
//使用web3j中的sha3算法:keccak-256
SHA3Digest digestSha3 = new SHA3Digest();
byte[] digest = digestSha3.hash(pdfFileByte);
- return "0x" + org.bcos.web3j.crypto.sm2.util.encoders.Hex.toHexString(digest);
+ return Numeric.toHexString(digest);
}
/**
diff --git a/src/main/java/com/webank/weid/util/CredentialUtils.java b/src/main/java/com/webank/weid/util/CredentialUtils.java
index 7a8e0c7e..4344fd30 100644
--- a/src/main/java/com/webank/weid/util/CredentialUtils.java
+++ b/src/main/java/com/webank/weid/util/CredentialUtils.java
@@ -31,8 +31,7 @@
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
-import org.bcos.web3j.abi.datatypes.generated.Bytes32;
-import org.bcos.web3j.crypto.Sign;
+import org.fisco.bcos.web3j.abi.datatypes.generated.Bytes32;
import com.webank.weid.constant.CredentialConstant;
import com.webank.weid.constant.CredentialConstant.CredentialProofType;
diff --git a/src/main/java/com/webank/weid/util/DataToolUtils.java b/src/main/java/com/webank/weid/util/DataToolUtils.java
index bbc7e5ae..f96d9ce6 100644
--- a/src/main/java/com/webank/weid/util/DataToolUtils.java
+++ b/src/main/java/com/webank/weid/util/DataToolUtils.java
@@ -78,25 +78,25 @@
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
-import org.bcos.web3j.abi.datatypes.Address;
-import org.bcos.web3j.abi.datatypes.DynamicArray;
-import org.bcos.web3j.abi.datatypes.DynamicBytes;
-import org.bcos.web3j.abi.datatypes.StaticArray;
-import org.bcos.web3j.abi.datatypes.generated.Bytes32;
-import org.bcos.web3j.abi.datatypes.generated.Int256;
-import org.bcos.web3j.abi.datatypes.generated.Uint256;
-import org.bcos.web3j.abi.datatypes.generated.Uint8;
-import org.bcos.web3j.crypto.ECKeyPair;
-import org.bcos.web3j.crypto.Hash;
-import org.bcos.web3j.crypto.Keys;
-import org.bcos.web3j.crypto.Sign;
-import org.bcos.web3j.crypto.Sign.SignatureData;
-import org.bcos.web3j.utils.Numeric;
import org.bouncycastle.util.encoders.Base64;
+import org.fisco.bcos.web3j.abi.datatypes.Address;
+import org.fisco.bcos.web3j.abi.datatypes.DynamicArray;
+import org.fisco.bcos.web3j.abi.datatypes.DynamicBytes;
+import org.fisco.bcos.web3j.abi.datatypes.StaticArray;
+import org.fisco.bcos.web3j.abi.datatypes.generated.Bytes32;
+import org.fisco.bcos.web3j.abi.datatypes.generated.Int256;
+import org.fisco.bcos.web3j.abi.datatypes.generated.Uint256;
+import org.fisco.bcos.web3j.abi.datatypes.generated.Uint8;
import org.fisco.bcos.web3j.crypto.ECDSASign;
import org.fisco.bcos.web3j.crypto.ECDSASignature;
+import org.fisco.bcos.web3j.crypto.ECKeyPair;
+import org.fisco.bcos.web3j.crypto.Hash;
+import org.fisco.bcos.web3j.crypto.Keys;
+import org.fisco.bcos.web3j.crypto.Sign;
+import org.fisco.bcos.web3j.crypto.Sign.SignatureData;
import org.fisco.bcos.web3j.crypto.tool.ECCDecrypt;
import org.fisco.bcos.web3j.crypto.tool.ECCEncrypt;
+import org.fisco.bcos.web3j.utils.Numeric;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -239,11 +239,11 @@ public static String serialize(T object) {
* @return true if yes, false otherwise
*/
public static String convertPrivateKeyToDefaultWeId(String privateKey) {
- org.fisco.bcos.web3j.crypto.ECKeyPair keyPair = org.fisco.bcos.web3j.crypto.ECKeyPair
+ ECKeyPair keyPair = ECKeyPair
.create(new BigInteger(privateKey));
return WeIdUtils
.convertAddressToWeId(new org.fisco.bcos.web3j.abi.datatypes.Address(
- org.fisco.bcos.web3j.crypto.Keys.getAddress(keyPair)).toString());
+ Keys.getAddress(keyPair)).toString());
}
/**
@@ -486,50 +486,41 @@ public static ECKeyPair createKeyPair()
}
/**
- * Sign a message based on the given key-pairs. The message passed in WILL BE HASHED.
+ * Secp256k1 sign.
*
- * @param message the message
- * @param keyPair the key pair
- * @return SignatureData
+ * @param rawData original raw data
+ * @param privateKey private key in BigInteger format
+ * @return base64 string for signature value
*/
- public static Sign.SignatureData signMessage(String message, ECKeyPair keyPair) {
- return Sign.signMessage(sha3(message.getBytes(StandardCharsets.UTF_8)), keyPair);
+ public static String secp256k1Sign(String rawData, BigInteger privateKey) {
+ SignatureData sigData = secp256k1SignToSignature(rawData, privateKey);
+ return secp256k1SigBase64Serialization(sigData);
}
-
+
/**
- * Sign a message based on the given privateKey in Decimal String BigInt. The message passed in
- * WILL BE HASHED.
+ * Secp256k1 sign to Signature.
*
- * @param message the message
- * @param privateKeyString the private key string
- * @return SignatureData
+ * @param rawData original raw data
+ * @param keyPair keyPair
+ * @return SignatureData for signature value
*/
- @Deprecated
- public static Sign.SignatureData signMessage(
- String message,
- String privateKeyString) {
-
- BigInteger privateKey = new BigInteger(privateKeyString);
- ECKeyPair keyPair = new ECKeyPair(privateKey, publicKeyFromPrivate(privateKey));
- return Sign.signMessage(sha3(message.getBytes(StandardCharsets.UTF_8)), keyPair);
+ public static SignatureData secp256k1SignToSignature(String rawData, ECKeyPair keyPair) {
+ ECDSASign ecdsaSign = new ECDSASign();
+ return ecdsaSign.secp256SignMessage(rawData.getBytes(), keyPair);
}
-
+
/**
- * Secp256k1 sign.
+ * Secp256k1 sign to Signature.
*
* @param rawData original raw data
* @param privateKey private key in BigInteger format
- * @return base64 string for signature value
+ * @return SignatureData for signature value
*/
- public static String secp256k1Sign(String rawData, BigInteger privateKey) {
- ECDSASign ecdsaSign = new ECDSASign();
- org.fisco.bcos.web3j.crypto.ECKeyPair keyPair = org.fisco.bcos.web3j.crypto.ECKeyPair
- .create(privateKey);
- org.fisco.bcos.web3j.crypto.Sign.SignatureData sigData = ecdsaSign
- .secp256SignMessage(rawData.getBytes(), keyPair);
- return secp256k1SigBase64Serialization(sigData);
+ public static SignatureData secp256k1SignToSignature(String rawData, BigInteger privateKey) {
+ ECKeyPair keyPair = ECKeyPair.create(privateKey);
+ return secp256k1SignToSignature(rawData, keyPair);
}
-
+
/**
* Serialize secp256k1 signature into base64 encoded, in R, S, V (0, 1) format.
*
@@ -537,7 +528,7 @@ public static String secp256k1Sign(String rawData, BigInteger privateKey) {
* @return base64 string
*/
public static String secp256k1SigBase64Serialization(
- org.fisco.bcos.web3j.crypto.Sign.SignatureData sigData) {
+ SignatureData sigData) {
byte[] sigBytes = new byte[65];
sigBytes[64] = sigData.getV();
System.arraycopy(sigData.getR(), 0, sigBytes, 0, 32);
@@ -551,7 +542,7 @@ public static String secp256k1SigBase64Serialization(
* @param signature signature base64 string
* @return secp256k1 signature (v = 0,1)
*/
- public static org.fisco.bcos.web3j.crypto.Sign.SignatureData secp256k1SigBase64Deserialization(
+ public static SignatureData secp256k1SigBase64Deserialization(
String signature
) {
byte[] sigBytes = base64Decode(signature.getBytes(StandardCharsets.UTF_8));
@@ -559,7 +550,7 @@ public static org.fisco.bcos.web3j.crypto.Sign.SignatureData secp256k1SigBase64D
byte[] s = new byte[32];
System.arraycopy(sigBytes, 0, r, 0, 32);
System.arraycopy(sigBytes, 32, s, 0, 32);
- return new org.fisco.bcos.web3j.crypto.Sign.SignatureData(sigBytes[64], r, s);
+ return new SignatureData(sigBytes[64], r, s);
}
/**
@@ -579,7 +570,7 @@ public static boolean verifySecp256k1Signature(
if (rawData == null) {
return false;
}
- org.fisco.bcos.web3j.crypto.Sign.SignatureData sigData =
+ SignatureData sigData =
secp256k1SigBase64Deserialization(signatureBase64);
ECDSASign ecdsaSign = new ECDSASign();
byte[] hashBytes = Hash.sha3(rawData.getBytes());
@@ -598,11 +589,11 @@ public static boolean verifySecp256k1Signature(
* @return WeID
*/
public static String recoverWeIdFromMsgAndSecp256Sig(String rawData, String sigBase64) {
- org.fisco.bcos.web3j.crypto.Sign.SignatureData sigData = secp256k1SigBase64Deserialization(
+ SignatureData sigData = secp256k1SigBase64Deserialization(
sigBase64);
byte[] hashBytes = Hash.sha3(rawData.getBytes());
- org.fisco.bcos.web3j.crypto.Sign.SignatureData modifiedSigData =
- new org.fisco.bcos.web3j.crypto.Sign.SignatureData(
+ SignatureData modifiedSigData =
+ new SignatureData(
(byte) (sigData.getV() + 27),
sigData.getR(),
sigData.getS());
@@ -610,30 +601,11 @@ public static String recoverWeIdFromMsgAndSecp256Sig(String rawData, String sigB
new ECDSASignature(
org.fisco.bcos.web3j.utils.Numeric.toBigInt(modifiedSigData.getR()),
org.fisco.bcos.web3j.utils.Numeric.toBigInt(modifiedSigData.getS()));
- BigInteger k = org.fisco.bcos.web3j.crypto.Sign
+ BigInteger k = Sign
.recoverFromSignature(modifiedSigData.getV() - 27, sig, hashBytes);
return WeIdUtils.convertPublicKeyToWeId(k.toString(10));
}
- /**
- * Sign a object based on the given privateKey in Decimal String BigInt.
- *
- * @param rawData this rawData to be signed,
- * @param privateKeyString the private key string
- * @return String the data after signature
- */
- @Deprecated
- public static String sign(
- String rawData,
- String privateKeyString) {
-
- Sign.SignatureData sigData = signMessage(rawData, privateKeyString);
- return new String(
- base64Encode(simpleSignatureSerialization(sigData)),
- StandardCharsets.UTF_8
- );
- }
-
/**
* Extract the Public Key from the message and the SignatureData.
*
@@ -650,55 +622,11 @@ public static BigInteger signatureToPublicKey(
return Sign.signedMessageToKey(sha3(message.getBytes(StandardCharsets.UTF_8)),
signatureData);
} catch (Exception e) {
+ e.printStackTrace();
throw new SignatureException(e);
}
}
- /**
- * Verify whether the message and the Signature matches the given public Key.
- *
- * @param message This should be from the same plain-text source with the signature Data.
- * @param signatureData This must be in SignatureData. Caller should call deserialize.
- * @param publicKey This must be in BigInteger. Callseer should convert it to BigInt.
- * @return true if yes, false otherwise
- * @throws SignatureException Signature is the exception.
- */
- public static boolean verifySignature(
- String message,
- Sign.SignatureData signatureData,
- BigInteger publicKey)
- throws SignatureException {
- if (message == null) {
- return false;
- }
- BigInteger extractedPublicKey = signatureToPublicKey(message, signatureData);
- return extractedPublicKey.equals(publicKey);
- }
-
- /**
- * Verify whether the message and the Signature matches the given public Key.
- *
- * @param message This should be from the same plain-text source with the signature Data.
- * @param signature this is a signature string of Base64.
- * @param publicKey This must be in BigInteger. Caller should convert it to BigInt.
- * @return true if yes, false otherwise
- */
- public static boolean verifySignature(
- String message,
- String signature,
- BigInteger publicKey) {
- try {
- if (message == null) {
- return false;
- }
- Sign.SignatureData signatureData = convertBase64StringToSignatureData(signature);
- BigInteger extractedPublicKey = signatureToPublicKey(message, signatureData);
- return extractedPublicKey.equals(publicKey);
- } catch (SignatureException e) {
- return false;
- }
- }
-
/**
* eecrypt the data.
*
@@ -902,97 +830,6 @@ public static ErrorCode verifySecp256k1SignatureFromWeId(
return ErrorCode.SUCCESS;
}
- /**
- * Verify a signature based on the provided raw data, and the WeID Document from chain. This
- * will traverse each public key in the WeID Document and fetch all keys which belongs to the
- * authentication list. Then, verify signature to each one; return true if anyone matches. This
- * is used for object checking.
- *
- * @param rawData the rawData to be verified
- * @param signature the Signature Data
- * @param weIdDocument the WeIdDocument to be extracted
- * @param weIdPublicKeyId the WeID public key ID
- * @return true if yes, false otherwise with exact error codes
- */
- public static ErrorCode verifySignatureFromWeId(
- String rawData,
- String signature,
- WeIdDocument weIdDocument,
- String weIdPublicKeyId) {
- Sign.SignatureData signatureData = null;
- try {
- signatureData = convertBase64StringToSignatureData(signature);
- } catch (Exception e) {
- logger.error("verify Signature failed.", e);
- return ErrorCode.CREDENTIAL_SIGNATURE_BROKEN;
- }
- return verifySignatureFromWeId(rawData, signatureData, weIdDocument, weIdPublicKeyId);
- }
-
- /**
- * Verify a signature based on the provided raw data, and the WeID Document from chain. This
- * will traverse each public key in the WeID Document and fetch all keys which belongs to the
- * authentication list. Then, verify signature to each one; return true if anyone matches. This
- * is used in CredentialService and EvidenceService.
- *
- * @param rawData the rawData to be verified
- * @param signatureData the Signature Data structure
- * @param weIdDocument the WeIdDocument to be extracted
- * @param weIdPublicKeyId the WeID public key ID
- * @return true if yes, false otherwise with exact error codes
- */
- public static ErrorCode verifySignatureFromWeId(
- String rawData,
- Sign.SignatureData signatureData,
- WeIdDocument weIdDocument,
- String weIdPublicKeyId) {
- List publicKeysListToVerify = new ArrayList();
-
- // Traverse public key list indexed Authentication key list
- for (PublicKeyProperty publicKeyProperty : weIdDocument.getPublicKey()) {
- if (publicKeyProperty.getRevoked()) {
- continue;
- }
- publicKeysListToVerify.add(publicKeyProperty.getPublicKey());
- }
- String foundMatchingPubKeyId = StringUtils.EMPTY;
- try {
- boolean result = false;
- for (String publicKeyItem : publicKeysListToVerify) {
- if (StringUtils.isNotEmpty(publicKeyItem)) {
- boolean currentResult = verifySignature(
- rawData, signatureData, new BigInteger(publicKeyItem));
- result = result || currentResult;
- if (currentResult) {
- for (PublicKeyProperty pkp : weIdDocument.getPublicKey()) {
- if (pkp.getRevoked()) {
- continue;
- }
- if (pkp.getPublicKey().equalsIgnoreCase(publicKeyItem)) {
- foundMatchingPubKeyId = pkp.getId();
- }
- }
- break;
- }
- }
- }
- if (!result) {
- return ErrorCode.CREDENTIAL_VERIFY_FAIL;
- }
- } catch (SignatureException e) {
- logger.error("some exceptions occurred in signature verification", e);
- return ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE;
- }
- if (NumberUtils.isDigits(weIdPublicKeyId)) {
- weIdPublicKeyId = weIdDocument.getId() + "#keys-" + Integer.valueOf(weIdPublicKeyId);
- }
- if (!StringUtils.isEmpty(weIdPublicKeyId)
- && !foundMatchingPubKeyId.equalsIgnoreCase(weIdPublicKeyId)) {
- return ErrorCode.CREDENTIAL_VERIFY_SUCCEEDED_WITH_WRONG_PUBLIC_KEY_ID;
- }
- return ErrorCode.SUCCESS;
- }
-
/**
* Convert SignatureData to blockchain-ready RSV format.
*
diff --git a/src/main/java/com/webank/weid/util/DateUtils.java b/src/main/java/com/webank/weid/util/DateUtils.java
index c60cb411..da0ba0dd 100644
--- a/src/main/java/com/webank/weid/util/DateUtils.java
+++ b/src/main/java/com/webank/weid/util/DateUtils.java
@@ -30,7 +30,7 @@
import java.util.Date;
import java.util.TimeZone;
-import org.bcos.web3j.abi.datatypes.generated.Int256;
+import org.fisco.bcos.web3j.abi.datatypes.generated.Int256;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
diff --git a/src/main/java/com/webank/weid/util/TransactionUtils.java b/src/main/java/com/webank/weid/util/TransactionUtils.java
index 90adb6d2..883d526d 100644
--- a/src/main/java/com/webank/weid/util/TransactionUtils.java
+++ b/src/main/java/com/webank/weid/util/TransactionUtils.java
@@ -19,7 +19,6 @@
package com.webank.weid.util;
-import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
@@ -27,37 +26,22 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.Optional;
import java.util.Random;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
-import java.util.stream.Collectors;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
-import org.bcos.channel.client.Service;
-import org.bcos.channel.handler.ChannelConnections;
-import org.bcos.web3j.abi.datatypes.Address;
-import org.bcos.web3j.abi.datatypes.DynamicBytes;
-import org.bcos.web3j.abi.datatypes.StaticArray;
-import org.bcos.web3j.abi.datatypes.Type;
-import org.bcos.web3j.abi.datatypes.generated.Bytes32;
-import org.bcos.web3j.abi.datatypes.generated.Int256;
-import org.bcos.web3j.abi.datatypes.generated.Uint256;
-import org.bcos.web3j.protocol.Web3j;
-import org.bcos.web3j.protocol.core.DefaultBlockParameterNumber;
-import org.bcos.web3j.protocol.core.methods.response.EthBlock;
-import org.bcos.web3j.protocol.core.methods.response.EthGetTransactionReceipt;
-import org.bcos.web3j.protocol.core.methods.response.EthSendTransaction;
-import org.bcos.web3j.protocol.core.methods.response.Transaction;
-import org.bcos.web3j.protocol.core.methods.response.TransactionReceipt;
-import org.bcos.web3j.protocol.exceptions.TransactionTimeoutException;
+import org.fisco.bcos.web3j.abi.datatypes.Address;
+import org.fisco.bcos.web3j.abi.datatypes.DynamicBytes;
+import org.fisco.bcos.web3j.abi.datatypes.StaticArray;
+import org.fisco.bcos.web3j.abi.datatypes.Type;
+import org.fisco.bcos.web3j.abi.datatypes.generated.Bytes32;
+import org.fisco.bcos.web3j.abi.datatypes.generated.Int256;
+import org.fisco.bcos.web3j.abi.datatypes.generated.Uint256;
+import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
-import com.webank.weid.config.FiscoConfig;
import com.webank.weid.constant.ErrorCode;
import com.webank.weid.constant.JsonSchemaConstant;
import com.webank.weid.constant.ParamKeyConstant;
@@ -66,7 +50,6 @@
import com.webank.weid.protocol.response.ResponseData;
import com.webank.weid.protocol.response.RsvSignature;
import com.webank.weid.protocol.response.TransactionInfo;
-import com.webank.weid.service.BaseService;
/**
* Transaction related utility functions. This class handles specific Transaction tasks, including
@@ -79,63 +62,6 @@ public class TransactionUtils {
private static final Logger logger = LoggerFactory.getLogger(TransactionUtils.class);
- /**
- * Send a transaction to blockchain through web3j instance using the transactionHex value.
- *
- * @param web3j the web3j instance to blockchain
- * @param transactionHex the transactionHex value
- * @return the transactionReceipt
- * @throws Exception the exception
- */
- public static TransactionReceipt sendTransaction(Web3j web3j, String transactionHex)
- throws Exception {
- if (web3j == null || StringUtils.isEmpty(transactionHex)) {
- return null;
- }
- EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(transactionHex)
- .sendAsync().get(WeIdConstant.TRANSACTION_RECEIPT_TIMEOUT, TimeUnit.SECONDS);
- if (ethSendTransaction.hasError()) {
- logger.error("Error processing transaction request: "
- + ethSendTransaction.getError().getMessage());
- return null;
- }
- Optional receiptOptional =
- getTransactionReceiptRequest(web3j, ethSendTransaction.getTransactionHash());
- int sumTime = 0;
- try {
- for (int i = 0; i < WeIdConstant.POLL_TRANSACTION_ATTEMPTS; i++) {
- if (!receiptOptional.isPresent()) {
- Thread.sleep((long) WeIdConstant.POLL_TRANSACTION_SLEEP_DURATION);
- sumTime += WeIdConstant.POLL_TRANSACTION_SLEEP_DURATION;
- receiptOptional = getTransactionReceiptRequest(web3j,
- ethSendTransaction.getTransactionHash());
- } else {
- return receiptOptional.get();
- }
- }
- } catch (Exception e) {
- throw new TransactionTimeoutException("Transaction receipt was not generated after "
- + ((sumTime) / 1000
- + " seconds for transaction: " + ethSendTransaction));
- }
- return null;
- }
-
- /**
- * Get a default blocklimit for a transaction. Used by Restful API service.
- *
- * @return blocklimit in BigInt.
- */
- public static BigInteger getBlockLimit() {
- try {
- return ((Web3j) BaseService.getWeb3j()).ethBlockNumber().send().getBlockNumber()
- .add(new BigInteger(String.valueOf(WeIdConstant.ADDITIVE_BLOCK_HEIGHT)));
- } catch (Exception e) {
- //Send a large enough block limit number
- return new BigInteger(WeIdConstant.BIG_BLOCK_LIMIT);
- }
- }
-
/**
* Check validity and build input params for createWeId (with attributes - public key) function.
* Used by Restful API service.
@@ -356,26 +282,6 @@ public static StaticArray getParamJsonSchema(String cptJsonSchema) {
return DataToolUtils.byteArrayListToBytes32StaticArray(bytes);
}
- /**
- * Get a TransactionReceipt request from a transaction Hash.
- *
- * @param web3j the web3j instance to blockchain
- * @param transactionHash the transactionHash value
- * @return the transactionReceipt wrapper
- * @throws Exception the exception
- */
- private static Optional getTransactionReceiptRequest(Web3j web3j,
- String transactionHash) throws Exception {
- EthGetTransactionReceipt transactionReceipt =
- web3j.ethGetTransactionReceipt(transactionHash).send();
- if (transactionReceipt.hasError()) {
- logger.error("Error processing transaction request: "
- + transactionReceipt.getError().getMessage());
- return Optional.empty();
- }
- return transactionReceipt.getTransactionReceipt();
- }
-
/**
* Get a random Nonce for a transaction. Used by Restful API service.
*
@@ -503,106 +409,4 @@ public static ResponseData getResultByResolveEvent(
info);
return responseData;
}
-
- /**
- * Get the transaction instance from blockchain. Requires an on-chain Read operation.
- *
- * @param info the transaction info
- * @return the transaction
- */
- public static Transaction getTransaction(TransactionInfo info) {
- if (info == null) {
- return null;
- }
- Web3j web3j = (Web3j) BaseService.getWeb3j();
- EthBlock ethBlock = null;
- BigInteger blockNumber = info.getBlockNumber();
- try {
- ethBlock = web3j
- .ethGetBlockByNumber(new DefaultBlockParameterNumber(blockNumber), true).send();
- } catch (IOException e) {
- logger.error("Cannot get a block with number: {}. Error: {}", blockNumber, e);
- }
- if (ethBlock == null) {
- logger.error("Block number {} is null", blockNumber);
- return null;
- }
- List transactionList;
- try {
- transactionList = getTransactionListFromBlock(ethBlock);
- } catch (Exception e) {
- logger.error(
- "Error occurred during getting transaction list with block number: {}. Error: {}",
- blockNumber, e);
- return null;
- }
- if (transactionList.size() == 0) {
- logger.error("Cannot get any transaction with block number: {}", blockNumber);
- return null;
- }
- return getTransactionFromList(transactionList, info);
- }
-
- /**
- * Build a FISCO-BCOS Service instance based on the given FISCO-BCOS config bundle.
- *
- * @param fiscoConfig the FiscoConfig
- * @return Service instance client
- */
- public static Service buildFiscoBcosService(FiscoConfig fiscoConfig) {
- if (!fiscoConfig.getVersion().startsWith(WeIdConstant.FISCO_BCOS_1_X_VERSION_PREFIX)) {
- logger.error("Only 1.x version FISCO-BCOS chain configurations are allowed. Abort.");
- return null;
- }
- String currentOrgId = PropertyUtils.getProperty("blockchain.orgid");
- Service service = new Service();
- service.setOrgID(currentOrgId);
- service.setConnectSeconds(Integer.valueOf(fiscoConfig.getWeb3sdkTimeout()));
-
- // connection params
- ChannelConnections channelConnections = new ChannelConnections();
- channelConnections.setCaCertPath("classpath:" + fiscoConfig.getV1CaCrtPath());
- channelConnections.setClientCertPassWord(fiscoConfig.getV1ClientCrtPassword());
- channelConnections
- .setClientKeystorePath("classpath:" + fiscoConfig.getV1ClientKeyStorePath());
- channelConnections.setKeystorePassWord(fiscoConfig.getV1KeyStorePassword());
- channelConnections.setConnectionsStr(Arrays.asList(fiscoConfig.getNodes().split(",")));
- ConcurrentHashMap allChannelConnections =
- new ConcurrentHashMap<>();
- allChannelConnections.put(currentOrgId, channelConnections);
- service.setAllChannelConnections(allChannelConnections);
-
- // thread pool params
- ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
- pool.setBeanName("web3sdk");
- pool.setCorePoolSize(Integer.valueOf(fiscoConfig.getWeb3sdkCorePoolSize()));
- pool.setMaxPoolSize(Integer.valueOf(fiscoConfig.getWeb3sdkMaxPoolSize()));
- pool.setQueueCapacity(Integer.valueOf(fiscoConfig.getWeb3sdkQueueSize()));
- pool.setKeepAliveSeconds(Integer.valueOf(fiscoConfig.getWeb3sdkKeepAliveSeconds()));
- pool.setRejectedExecutionHandler(new java.util.concurrent.ThreadPoolExecutor.AbortPolicy());
- pool.initialize();
- service.setThreadPool(pool);
- return service;
- }
-
- private static List getTransactionListFromBlock(EthBlock ethBlock) {
- return ethBlock
- .getBlock()
- .getTransactions()
- .stream()
- .map(transactionResult -> (Transaction) transactionResult.get())
- .collect(Collectors.toList());
- }
-
- private static Transaction getTransactionFromList(List transactionList,
- TransactionInfo info) {
- for (Transaction transaction : transactionList) {
- if (transaction.getHash().equalsIgnoreCase(info.getTransactionHash())
- && transaction.getTransactionIndex().longValue() == info.getTransactionIndex()
- .longValue()) {
- return transaction;
- }
- }
- return null;
- }
}
diff --git a/src/main/java/com/webank/weid/util/WeIdUtils.java b/src/main/java/com/webank/weid/util/WeIdUtils.java
index 7766d7a0..d7cbf46d 100644
--- a/src/main/java/com/webank/weid/util/WeIdUtils.java
+++ b/src/main/java/com/webank/weid/util/WeIdUtils.java
@@ -24,10 +24,10 @@
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
-import org.bcos.web3j.abi.datatypes.Address;
-import org.bcos.web3j.crypto.ECKeyPair;
-import org.bcos.web3j.crypto.WalletUtils;
+import org.fisco.bcos.web3j.abi.datatypes.Address;
+import org.fisco.bcos.web3j.crypto.ECKeyPair;
import org.fisco.bcos.web3j.crypto.Keys;
+import org.fisco.bcos.web3j.crypto.WalletUtils;
import org.fisco.bcos.web3j.utils.Numeric;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -197,16 +197,6 @@ public static boolean isEmptyAddress(Address addr) {
return addr.getValue().equals(BigInteger.ZERO);
}
- /**
- * check if the given Address is empty.
- *
- * @param addr given Address
- * @return true if yes, false otherwise.
- */
- public static boolean isEmptyAddress(org.fisco.bcos.web3j.abi.datatypes.Address addr) {
- return addr.getValue().equals(BigInteger.ZERO);
- }
-
/**
* check if the given Address is empty.
*
diff --git a/src/test/java/com/webank/weid/full/TestBaseUtil.java b/src/test/java/com/webank/weid/full/TestBaseUtil.java
index ef6c6763..042f94de 100644
--- a/src/test/java/com/webank/weid/full/TestBaseUtil.java
+++ b/src/test/java/com/webank/weid/full/TestBaseUtil.java
@@ -37,8 +37,8 @@
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonLoader;
import org.apache.commons.lang3.StringUtils;
-import org.bcos.web3j.crypto.ECKeyPair;
-import org.bcos.web3j.crypto.Keys;
+import org.fisco.bcos.web3j.crypto.ECKeyPair;
+import org.fisco.bcos.web3j.crypto.Keys;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
diff --git a/src/test/java/com/webank/weid/full/credential/TestCreateCredential.java b/src/test/java/com/webank/weid/full/credential/TestCreateCredential.java
index 4f2b69a7..c478bd16 100644
--- a/src/test/java/com/webank/weid/full/credential/TestCreateCredential.java
+++ b/src/test/java/com/webank/weid/full/credential/TestCreateCredential.java
@@ -394,7 +394,7 @@ public void testCreateCredential_priKeyNotMatch() {
Assert.assertNotNull(response.getResult());
ResponseData verify = credentialService.verify(response.getResult());
- Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(),
+ Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(),
verify.getErrorCode().intValue());
}
@@ -417,7 +417,7 @@ public void testCreateCredential_sdkPriKey() {
Assert.assertEquals(ErrorCode.SUCCESS.getCode(), response.getErrorCode().intValue());
ResponseData verify = credentialService.verify(response.getResult());
- Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(),
+ Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(),
verify.getErrorCode().intValue());
}
diff --git a/src/test/java/com/webank/weid/full/credential/TestVerifyCredential.java b/src/test/java/com/webank/weid/full/credential/TestVerifyCredential.java
index a8059cf7..bdf2a4dd 100644
--- a/src/test/java/com/webank/weid/full/credential/TestVerifyCredential.java
+++ b/src/test/java/com/webank/weid/full/credential/TestVerifyCredential.java
@@ -25,7 +25,7 @@
import mockit.Mock;
import mockit.MockUp;
import org.apache.commons.lang3.StringUtils;
-import org.bcos.web3j.crypto.Sign;
+import org.fisco.bcos.web3j.crypto.Sign;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
@@ -114,7 +114,7 @@ public void testVerifyCredential_contentIsOtherString() {
LogUtil.info(logger, "verifyCredential", response);
credential.setContext(context);
- Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(),
+ Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(),
response.getErrorCode().intValue());
Assert.assertEquals(false, response.getResult());
}
@@ -151,7 +151,7 @@ public void testVerifyCredential_cptIdAndClaimDifferent() {
LogUtil.info(logger, "verifyCredential", response);
credential.setCptId(cptId);
- Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(),
+ Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(),
response.getErrorCode().intValue());
Assert.assertEquals(false, response.getResult());
}
@@ -258,7 +258,7 @@ public void testVerifyCredential_otherIssuer() {
LogUtil.info(logger, "verifyCredential", response);
credential.setIssuer(issuer);
- Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(),
+ Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(),
response.getErrorCode().intValue());
Assert.assertEquals(false, response.getResult());
}
@@ -400,7 +400,7 @@ public Sign.SignatureData simpleSignatureDeserialization(
ResponseData response = super.verifyCredential(credential);
LogUtil.info(logger, "verifyCredential", response);
- Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(),
+ Assert.assertEquals(ErrorCode.CREDENTIAL_ERROR.getCode(),
response.getErrorCode().intValue());
Assert.assertEquals(false, response.getResult());
}
@@ -476,7 +476,7 @@ public void testVerifyCredentialCase24() {
ResponseData response = super.verifyCredential(credentialWrapper.getCredential());
LogUtil.info(logger, "verifyCredential", response);
- Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(),
+ Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(),
response.getErrorCode().intValue());
Assert.assertEquals(false, response.getResult());
}
diff --git a/src/test/java/com/webank/weid/full/credential/TestVerifyCredentialWithSpecifiedPubKey.java b/src/test/java/com/webank/weid/full/credential/TestVerifyCredentialWithSpecifiedPubKey.java
index a4d3fc7e..5be00cdb 100644
--- a/src/test/java/com/webank/weid/full/credential/TestVerifyCredentialWithSpecifiedPubKey.java
+++ b/src/test/java/com/webank/weid/full/credential/TestVerifyCredentialWithSpecifiedPubKey.java
@@ -98,7 +98,7 @@ public void testVerifyCredentialWithSpecifiedPubKeyCase2() {
credentialService.verifyCredentialWithSpecifiedPubKey(credentialWrapper, weIdPublicKey);
LogUtil.info(logger, "verifyCredentialWithSpecifiedPubKey", response);
- Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(),
+ Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(),
response.getErrorCode().intValue());
Assert.assertEquals(false, response.getResult());
}
diff --git a/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialByIssuer.java b/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialByIssuer.java
index f5d7ae9e..11ebddfe 100644
--- a/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialByIssuer.java
+++ b/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialByIssuer.java
@@ -19,13 +19,11 @@
package com.webank.weid.full.credentialpojo;
-import java.security.SignatureException;
import java.util.Map;
import mockit.Mock;
import mockit.MockUp;
import org.apache.commons.lang3.StringUtils;
-import org.bcos.web3j.crypto.Sign;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
@@ -42,7 +40,6 @@
import com.webank.weid.protocol.base.WeIdDocument;
import com.webank.weid.protocol.response.ResponseData;
import com.webank.weid.service.impl.WeIdServiceImpl;
-import com.webank.weid.util.DataToolUtils;
/**
* verifyCredentialPojo method for testing CredentialPojoService.
@@ -134,7 +131,7 @@ public void testVerifyCredential_contentError() {
ResponseData response = super.verifyCredentialPojo(copyCredentialPojo);
LogUtil.info(logger, "verifyCredential", response);
- Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(),
+ Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(),
response.getErrorCode().intValue());
Assert.assertEquals(false, response.getResult());
}
@@ -153,7 +150,7 @@ public void testVerifyCredential_otherCptId() {
ResponseData response = super.verifyCredentialPojo(copyCredentialPojo);
LogUtil.info(logger, "verifyCredential", response);
- Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(),
+ Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(),
response.getErrorCode().intValue());
Assert.assertEquals(false, response.getResult());
}
@@ -202,7 +199,7 @@ public void testVerifyCredential_OtherId() {
ResponseData response = super.verifyCredentialPojo(copyCredentialPojo);
LogUtil.info(logger, "verifyCredential", response);
- Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(),
+ Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(),
response.getErrorCode().intValue());
Assert.assertEquals(false, response.getResult());
}
@@ -253,7 +250,7 @@ public void testVerifyCredential_credentialPojoIssuerOther() {
ResponseData response = super.verifyCredentialPojo(copyCredentialPojo);
LogUtil.info(logger, "verifyCredential", response);
- Assert.assertEquals(ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode(),
+ Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(),
response.getErrorCode().intValue());
Assert.assertEquals(false, response.getResult());
}
diff --git a/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialByPublicKey.java b/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialByPublicKey.java
index 69878565..5da12957 100644
--- a/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialByPublicKey.java
+++ b/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialByPublicKey.java
@@ -494,7 +494,7 @@ public void testVerifyCredential_invalidSignature() {
newCredentialPojo);
LogUtil.info(logger, "verifyCredential", response);
- Assert.assertEquals(ErrorCode.CREDENTIAL_SIGNATURE_BROKEN.getCode(),
+ Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(),
response.getErrorCode().intValue());
Assert.assertEquals(false, response.getResult());
}
@@ -514,7 +514,7 @@ public void testVerifyCredential_signatureRnadom() {
newCredentialPojo);
LogUtil.info(logger, "verifyCredential", response);
- Assert.assertEquals(ErrorCode.CREDENTIAL_SIGNATURE_BROKEN.getCode(),
+ Assert.assertEquals(ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode(),
response.getErrorCode().intValue());
Assert.assertEquals(false, response.getResult());
}
diff --git a/src/test/java/com/webank/weid/full/evidence/TestCreateEvidence.java b/src/test/java/com/webank/weid/full/evidence/TestCreateEvidence.java
index ee40ee09..c2a258d6 100644
--- a/src/test/java/com/webank/weid/full/evidence/TestCreateEvidence.java
+++ b/src/test/java/com/webank/weid/full/evidence/TestCreateEvidence.java
@@ -20,6 +20,7 @@
package com.webank.weid.full.evidence;
import java.io.File;
+import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
@@ -139,7 +140,7 @@ public void testEvidenceManipulationFailures() {
// Here it should fail, since: signer's sig ! from privatekey
Assert.assertFalse(verifyResp.getResult());
Assert.assertEquals(verifyResp.getErrorCode().intValue(),
- ErrorCode.CREDENTIAL_EXCEPTION_VERIFYSIGNATURE.getCode());
+ ErrorCode.CREDENTIAL_VERIFY_FAIL.getCode());
//----
credential.setId(UUID.randomUUID().toString());
@@ -340,7 +341,8 @@ public void testBatchCreate() throws Exception {
String hash = credential.getHash();
hashValues.add(credential.getHash());
signatures.add(new String(DataToolUtils.base64Encode(DataToolUtils
- .simpleSignatureSerialization(DataToolUtils.signMessage(hash, privateKey))),
+ .simpleSignatureSerialization(DataToolUtils.secp256k1SignToSignature(
+ hash, new BigInteger(privateKey)))),
StandardCharsets.UTF_8));
timestamps.add(System.currentTimeMillis());
signers.add(DataToolUtils.convertPrivateKeyToDefaultWeId(privateKey));
@@ -430,7 +432,8 @@ public void testBatchCreateMultiGroup() {
List argList = new ArrayList<>();
argList.add(credential.getHash());
argList.add(new String(DataToolUtils.base64Encode(DataToolUtils
- .simpleSignatureSerialization(DataToolUtils.signMessage(hash, privateKey))),
+ .simpleSignatureSerialization(DataToolUtils.secp256k1SignToSignature(
+ hash, new BigInteger(privateKey)))),
StandardCharsets.UTF_8));
argList.add("test log" + i);
argList.add(DateUtils.getNoMillisecondTimeStampString());
diff --git a/src/test/java/com/webank/weid/full/weid/TestCreateWeId1.java b/src/test/java/com/webank/weid/full/weid/TestCreateWeId1.java
index 25974a4f..8219b38f 100644
--- a/src/test/java/com/webank/weid/full/weid/TestCreateWeId1.java
+++ b/src/test/java/com/webank/weid/full/weid/TestCreateWeId1.java
@@ -23,8 +23,8 @@
import mockit.Mock;
import mockit.MockUp;
-import org.bcos.web3j.crypto.ECKeyPair;
-import org.bcos.web3j.crypto.Keys;
+import org.fisco.bcos.web3j.crypto.ECKeyPair;
+import org.fisco.bcos.web3j.crypto.Keys;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
diff --git a/src/test/java/com/webank/weid/util/TestCrypt.java b/src/test/java/com/webank/weid/util/TestCrypt.java
index 3b4b1ba5..3a4abde1 100644
--- a/src/test/java/com/webank/weid/util/TestCrypt.java
+++ b/src/test/java/com/webank/weid/util/TestCrypt.java
@@ -19,8 +19,8 @@
package com.webank.weid.util;
-import org.bcos.web3j.crypto.ECKeyPair;
-import org.bcos.web3j.crypto.Keys;
+import org.fisco.bcos.web3j.crypto.ECKeyPair;
+import org.fisco.bcos.web3j.crypto.Keys;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
diff --git a/src/test/java/com/webank/weid/util/TestDataTypetUtils.java b/src/test/java/com/webank/weid/util/TestDataTypetUtils.java
index c95d4e42..3ddaf825 100644
--- a/src/test/java/com/webank/weid/util/TestDataTypetUtils.java
+++ b/src/test/java/com/webank/weid/util/TestDataTypetUtils.java
@@ -24,13 +24,13 @@
import java.util.List;
import java.util.UUID;
-import org.bcos.web3j.abi.datatypes.DynamicArray;
-import org.bcos.web3j.abi.datatypes.DynamicBytes;
-import org.bcos.web3j.abi.datatypes.StaticArray;
-import org.bcos.web3j.abi.datatypes.generated.Bytes32;
-import org.bcos.web3j.abi.datatypes.generated.Int256;
-import org.bcos.web3j.abi.datatypes.generated.Uint256;
-import org.bcos.web3j.abi.datatypes.generated.Uint8;
+import org.fisco.bcos.web3j.abi.datatypes.DynamicArray;
+import org.fisco.bcos.web3j.abi.datatypes.DynamicBytes;
+import org.fisco.bcos.web3j.abi.datatypes.StaticArray;
+import org.fisco.bcos.web3j.abi.datatypes.generated.Bytes32;
+import org.fisco.bcos.web3j.abi.datatypes.generated.Int256;
+import org.fisco.bcos.web3j.abi.datatypes.generated.Uint256;
+import org.fisco.bcos.web3j.abi.datatypes.generated.Uint8;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
diff --git a/src/test/java/com/webank/weid/util/TestDateUtils.java b/src/test/java/com/webank/weid/util/TestDateUtils.java
index 04f07b78..b48bcc77 100644
--- a/src/test/java/com/webank/weid/util/TestDateUtils.java
+++ b/src/test/java/com/webank/weid/util/TestDateUtils.java
@@ -25,7 +25,7 @@
import java.util.Date;
import java.util.TimeZone;
-import org.bcos.web3j.abi.datatypes.generated.Int256;
+import org.fisco.bcos.web3j.abi.datatypes.generated.Int256;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
diff --git a/src/test/java/com/webank/weid/util/TestSignatureUtils.java b/src/test/java/com/webank/weid/util/TestSignatureUtils.java
index 8367fff6..4a3ed5b5 100644
--- a/src/test/java/com/webank/weid/util/TestSignatureUtils.java
+++ b/src/test/java/com/webank/weid/util/TestSignatureUtils.java
@@ -20,11 +20,10 @@
package com.webank.weid.util;
import java.math.BigInteger;
-import java.security.SignatureException;
import com.lambdaworks.codec.Base64;
-import org.bcos.web3j.crypto.ECKeyPair;
-import org.bcos.web3j.crypto.Sign;
+import org.fisco.bcos.web3j.crypto.ECKeyPair;
+import org.fisco.bcos.web3j.crypto.Sign;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
@@ -43,28 +42,18 @@ public class TestSignatureUtils {
public void testSignatureUtils()
throws Exception {
- ECKeyPair keyPair = DataToolUtils.createKeyPair();
- String str = "hello world...........................yes";
- Sign.SignatureData sigData = DataToolUtils.signMessage(str, keyPair);
- BigInteger publicKey = DataToolUtils.signatureToPublicKey(str, sigData);
- logger.info("publicKey:{} ", publicKey);
-
String privateKey =
"58317564669857453586637110679746575832914889677346283755719850144028639639651";
- Sign.SignatureData sigData2 = DataToolUtils.signMessage(str, privateKey);
- publicKey = DataToolUtils.signatureToPublicKey(str, sigData2);
- logger.info("publicKey:{} ", publicKey);
-
- boolean result = DataToolUtils.verifySignature(str, sigData2, publicKey);
- Assert.assertTrue(result);
-
- publicKey = DataToolUtils.publicKeyFromPrivate(new BigInteger(privateKey));
+ BigInteger publicKey = DataToolUtils.publicKeyFromPrivate(new BigInteger(privateKey));
logger.info("publicKey:{} ", publicKey);
+ ECKeyPair keyPair = DataToolUtils.createKeyPair();
keyPair = DataToolUtils.createKeyPairFromPrivate(new BigInteger(privateKey));
logger.info("publicKey:{} ", keyPair.getPublicKey());
logger.info("privateKey:{}", keyPair.getPrivateKey());
+ String str = "hello world...........................yes";
+ Sign.SignatureData sigData = DataToolUtils.secp256k1SignToSignature(str, keyPair);
byte[] serialized = DataToolUtils.simpleSignatureSerialization(sigData);
Sign.SignatureData newSigData = DataToolUtils.simpleSignatureDeserialization(serialized);
logger.info(newSigData.toString());
diff --git a/src/test/java/com/webank/weid/util/TestTransactionUtils.java b/src/test/java/com/webank/weid/util/TestTransactionUtils.java
index 405b8217..12daa2ac 100644
--- a/src/test/java/com/webank/weid/util/TestTransactionUtils.java
+++ b/src/test/java/com/webank/weid/util/TestTransactionUtils.java
@@ -25,11 +25,11 @@
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
-import org.bcos.web3j.abi.datatypes.StaticArray;
-import org.bcos.web3j.abi.datatypes.Type;
-import org.bcos.web3j.abi.datatypes.generated.Bytes32;
-import org.bcos.web3j.abi.datatypes.generated.Int256;
-import org.bcos.web3j.protocol.core.methods.response.TransactionReceipt;
+import org.fisco.bcos.web3j.abi.datatypes.StaticArray;
+import org.fisco.bcos.web3j.abi.datatypes.Type;
+import org.fisco.bcos.web3j.abi.datatypes.generated.Bytes32;
+import org.fisco.bcos.web3j.abi.datatypes.generated.Int256;
+import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt;
import org.junit.Assert;
import org.junit.Test;
@@ -97,11 +97,5 @@ public void testBuildParams() throws Exception {
TransactionInfo info = new TransactionInfo(receipt);
Assert.assertNotNull(info);
Assert.assertNull(new TransactionInfo((TransactionReceipt) null).getBlockNumber());
- Assert.assertNull(TransactionUtils.getTransaction(null));
- }
-
- @Test
- public void testNullTransaction() throws Exception {
- Assert.assertNull(TransactionUtils.sendTransaction(null, StringUtils.EMPTY));
}
}
From 51eaac07620c9c10ff5d5aa7a89327fb494affd1 Mon Sep 17 00:00:00 2001
From: yg3630536 <125480926@qq.com>
Date: Thu, 15 Oct 2020 10:49:57 +0800
Subject: [PATCH 2/6] * get weid count and get activatedUserList from
databucket
---
build.gradle | 2 +-
.../com/webank/weid/constant/CnsType.java | 6 +-
.../contract/deploy/v2/RegisterAddressV2.java | 2 +-
.../java/com/webank/weid/rpc/WeIdService.java | 7 +
.../weid/service/impl/WeIdServiceImpl.java | 5 +
.../impl/engine/DataBucketServiceEngine.java | 68 ++++----
.../impl/engine/WeIdServiceEngine.java | 7 +
.../fiscov2/DataBucketServiceEngineV2.java | 148 +++++++++++-------
.../fiscov2/EvidenceServiceEngineV2.java | 3 +-
.../engine/fiscov2/WeIdServiceEngineV2.java | 11 ++
10 files changed, 171 insertions(+), 88 deletions(-)
diff --git a/build.gradle b/build.gradle
index 9069594e..9f848cc2 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.27-rc.4-SNAPSHOT") {
+ compile("com.webank:weid-contract-java:1.2.27-rc.5-SNAPSHOT") {
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 d5d263e3..4f919f37 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/contract/deploy/v2/RegisterAddressV2.java b/src/main/java/com/webank/weid/contract/deploy/v2/RegisterAddressV2.java
index b065605e..8fe3d04d 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/rpc/WeIdService.java b/src/main/java/com/webank/weid/rpc/WeIdService.java
index f5fdf66d..572e39ec 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/service/impl/WeIdServiceImpl.java b/src/main/java/com/webank/weid/service/impl/WeIdServiceImpl.java
index 381bbbd1..fbbc4ed5 100644
--- a/src/main/java/com/webank/weid/service/impl/WeIdServiceImpl.java
+++ b/src/main/java/com/webank/weid/service/impl/WeIdServiceImpl.java
@@ -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/engine/DataBucketServiceEngine.java b/src/main/java/com/webank/weid/service/impl/engine/DataBucketServiceEngine.java
index b0f0cd18..dd82317a 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/WeIdServiceEngine.java b/src/main/java/com/webank/weid/service/impl/engine/WeIdServiceEngine.java
index 60b05465..0c763047 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/fiscov2/DataBucketServiceEngineV2.java b/src/main/java/com/webank/weid/service/impl/engine/fiscov2/DataBucketServiceEngineV2.java
index 178f1918..279b3164 100644
--- a/src/main/java/com/webank/weid/service/impl/engine/fiscov2/DataBucketServiceEngineV2.java
+++ b/src/main/java/com/webank/weid/service/impl/engine/fiscov2/DataBucketServiceEngineV2.java
@@ -71,7 +71,7 @@ private DataBucket getDataBucket(String privateKey) {
@Override
public ResponseData put(
- String hash,
+ String bucketId,
String key,
String value,
WeIdPrivateKey privateKey) {
@@ -79,18 +79,20 @@ public ResponseData put(
Bytes32 keyByte32 = DataToolUtils.bytesArrayToBytes32(key.getBytes());
try {
TransactionReceipt receipt = getDataBucket(privateKey.getPrivateKey()).put(
- hash, keyByte32.getValue(), value).send();
+ bucketId, keyByte32.getValue(), value).send();
if (StringUtils
.equals(receipt.getStatus(), ParamKeyConstant.TRNSACTION_RECEIPT_STATUS_SUCCESS)) {
- logger.info("[put] put [{}:{}] into chain success, hash is {}.", key, value, hash);
+ logger.info("[put] put [{}:{}] into chain success, bucketId is {}.",
+ key, value, bucketId);
ErrorCode code = analysisErrorCode(receipt);
return new ResponseData(code == ErrorCode.SUCCESS, code);
}
- logger.error("[put] put [{}:{}] into chain fail, hash is {}.", key, value, hash);
+ logger.error("[put] put [{}:{}] into chain fail, bucketId is {}.",
+ key, value, bucketId);
return new ResponseData(false, ErrorCode.TRANSACTION_EXECUTE_ERROR);
} catch (Exception e) {
- logger.error("[put] put [{}:{}] into chain has excpetion, hash is {}, exception:",
- key, value, hash, e);
+ logger.error("[put] put [{}:{}] into chain has excpetion, bucketId is {}, exception:",
+ key, value, bucketId, e);
return new ResponseData(false, ErrorCode.UNKNOW_ERROR);
}
}
@@ -133,28 +135,30 @@ private ErrorCode analysisErrorCode(TransactionReceipt receipt) {
}
@Override
- public ResponseData get(String hash, String key) {
+ public ResponseData get(String bucketId, String key) {
Bytes32 keyByte32 = DataToolUtils.bytesArrayToBytes32(key.getBytes());
try {
- Tuple2 tuple = dataBucket.get(hash, keyByte32.getValue()).send();
+ Tuple2 tuple = dataBucket.get(
+ bucketId, keyByte32.getValue()).send();
int code = tuple.getValue1().intValue();
if (code == 102) {
- logger.error("[get] the hash does not exits, hash is {}.", hash);
+ logger.error("[get] the bucketId does not exits, bucketId is {}.", bucketId);
return new ResponseData(StringUtils.EMPTY, ErrorCode.CNS_DOES_NOT_EXIST);
}
- logger.info("[get] get address successfully, hash: {}, key: {}, value: {}",
- hash, key, tuple.getValue2());
+ logger.info("[get] get address successfully, bucketId: {}, key: {}, value: {}",
+ bucketId, key, tuple.getValue2());
return new ResponseData(tuple.getValue2(), ErrorCode.SUCCESS);
} catch (Exception e) {
logger.error(
- "[get] get data has exception, hash is {}, key is {}, exception:", hash, key, e);
+ "[get] get data has exception, bucketId is {}, key is {}, exception:",
+ bucketId, key, e);
return new ResponseData(StringUtils.EMPTY, ErrorCode.UNKNOW_ERROR);
}
}
@Override
public ResponseData removeExtraItem(
- String hash,
+ String bucketId,
String key,
WeIdPrivateKey privateKey
) {
@@ -165,46 +169,49 @@ public ResponseData removeExtraItem(
keyByte32 = DataToolUtils.bytesArrayToBytes32(key.getBytes());
}
try {
- logger.info("[remove] remove Extra Item, hash is {}, key is {}.", hash, key);
+ logger.info("[remove] remove Extra Item, bucketId is {}, key is {}.", bucketId, key);
TransactionReceipt receipt = getDataBucket(privateKey.getPrivateKey()).removeExtraItem(
- hash, keyByte32.getValue()).send();
+ bucketId, keyByte32.getValue()).send();
if (StringUtils
.equals(receipt.getStatus(), ParamKeyConstant.TRNSACTION_RECEIPT_STATUS_SUCCESS)) {
- logger.info("[remove] remove {} from chain success, hash is {}.", key, hash);
+ logger.info("[remove] remove {} from chain success, bucketId is {}.",
+ key, bucketId);
ErrorCode code = analysisErrorCode(receipt);
return new ResponseData(code == ErrorCode.SUCCESS, code);
}
- logger.error("[remove] remove {} from chain fail, hash is {}.", key, hash);
+ logger.error("[remove] remove {} from chain fail, bucketId is {}.", key, bucketId);
return new ResponseData(false, ErrorCode.TRANSACTION_EXECUTE_ERROR);
} catch (Exception e) {
- logger.error("[remove] remove {} from chain has excpetion, hash is {}, exception:",
- key, hash, e);
+ logger.error("[remove] remove {} from chain has excpetion, bucketId is {}, exception:",
+ key, bucketId, e);
return new ResponseData(false, ErrorCode.UNKNOW_ERROR);
}
}
@Override
public ResponseData removeDataBucketItem(
- String hash,
+ String bucketId,
boolean force,
WeIdPrivateKey privateKey
) {
try {
- logger.info("[remove] remove Bucket Item, hash is {}, force is {}.", hash, force);
+ logger.info("[remove] remove Bucket Item, bucketId is {}, force is {}.",
+ bucketId, force);
TransactionReceipt receipt = getDataBucket(privateKey.getPrivateKey())
- .removeDataBucketItem(hash, force).send();
+ .removeDataBucketItem(bucketId, force).send();
if (StringUtils
.equals(receipt.getStatus(), ParamKeyConstant.TRNSACTION_RECEIPT_STATUS_SUCCESS)) {
- logger.info("[remove] remove Bucket Item from chain success, hash is {}.", hash);
+ logger.info("[remove] remove Bucket Item from chain success, bucketId is {}.",
+ bucketId);
ErrorCode code = analysisErrorCode(receipt);
return new ResponseData(code == ErrorCode.SUCCESS, code);
}
- logger.error("[remove] remove Bucket Item from chain fail, hash is {}.", hash);
+ logger.error("[remove] remove Bucket Item from chain fail, bucketId is {}.", bucketId);
return new ResponseData(false, ErrorCode.TRANSACTION_EXECUTE_ERROR);
} catch (Exception e) {
logger.error(
- "[remove] remove Bucket Item from chain has excpetion, hash is {}, exception:",
- hash,
+ "[remove] remove Bucket Item from chain has excpetion, bucketId is {}, exception:",
+ bucketId,
e
);
return new ResponseData