diff --git a/CHANGELOG.md b/CHANGELOG.md index 2fc158775..6b0bf8b04 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +### V3.1.0 (2023-4-28) +- Features: +1. Add a way for local databases to deploy WeIdentity without deploying blockchain +- Bugfixes: +1. Upgrade components with known vulnerabilities + ### V3.0.0 (2022-12-15) - Features: 1. The project was restructured to strip the blockchain-related functions and interfaces from the project, as well as the file transfer and format conversion functions from the project diff --git a/VERSION b/VERSION index 3a580a21c..3b4a5be7d 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -3.0.0-rc.1 \ No newline at end of file +3.1.0-rc.1 \ No newline at end of file diff --git a/build.gradle b/build.gradle index 67e1f879b..1487faba9 100644 --- a/build.gradle +++ b/build.gradle @@ -80,7 +80,7 @@ List lombok = [ "org.projectlombok:lombok:1.18.10" ] -def log4j_version="2.18.0" +def log4j_version="2.20.0" List logger = [ "org.slf4j:jul-to-slf4j:1.7.30", "org.apache.logging.log4j:log4j-api:$log4j_version", @@ -106,7 +106,7 @@ List jmockit = [ "org.jmockit:jmockit:1.47" ] -def jackson_version="2.13.3" +def jackson_version="2.14.2" List json = [ "com.fasterxml.jackson.core:jackson-databind:$jackson_version", "com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:$jackson_version", @@ -116,7 +116,7 @@ List json = [ "com.networknt:json-schema-validator:1.0.71", ] -def gson_version = "2.8.9" +def gson_version = "2.10.1" List gson = [ "com.google.code.gson:gson:$gson_version" ] @@ -127,7 +127,7 @@ List mysql_driver = [ ] List redisson = [ - "org.redisson:redisson:3.13.1" + "org.redisson:redisson:3.20.0" ] List zxing = [ @@ -145,7 +145,7 @@ List pdfbox = [ ] List protobuf = [ - "com.google.protobuf:protobuf-java:3.19.2" + "com.google.protobuf:protobuf-java:3.22.2" ] List caffeine = [ @@ -156,8 +156,13 @@ List oval = [ "net.sf.oval:oval:3.2.1" ] +List xstream = [ + "com.thoughtworks.xstream:xstream:1.4.20" +] + List spring = [ - "org.springframework:spring-core:5.3.21" + "org.springframework:spring-core:5.3.21", + "org.springframework:spring-context:5.3.25" ] configurations { @@ -172,10 +177,9 @@ configurations.all { 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, gson + compile logger, lombok, apache_commons, json, mysql_driver, redisson, zxing, rpc, pdfbox, protobuf, caffeine, oval, gson, spring, xstream //compile("com.webank:weid-contract-java:1.3.1-rc.2-SNAPSHOT") - //compile("com.webank:weid-contract-java:1.3.1-rc1") - compile("com.webank:weid-blockchain:3.0.0-rc.1") + compile("com.webank:weid-blockchain:3.1.0-rc.1") compile fileTree(dir: 'lib', include: '*.jar') implementation 'com.google.guava:guava:31.1-jre' @@ -184,7 +188,7 @@ dependencies { implementation group: 'org.apache.httpcomponents', name: 'httpcore', version: '4.4.15' annotationProcessor lombok - testCompile logger, lombok, apache_commons, json, junit, jmockit, rpc, pdfbox, protobuf, caffeine, oval, spring, gson + testCompile logger, lombok, apache_commons, json, junit, jmockit, rpc, pdfbox, protobuf, caffeine, oval, spring, gson, xstream testAnnotationProcessor lombok } if (gradleVer.startsWith("4")) { diff --git a/dist/conf/fisco.properties.tpl b/dist/conf/fisco.properties.tpl index 09952d5cd..e368fa5d2 100644 --- a/dist/conf/fisco.properties.tpl +++ b/dist/conf/fisco.properties.tpl @@ -57,9 +57,9 @@ group.id=1 sdk.sm-crypto=${SDK_SM_CRYPTO} # fisco-bcos sdk cert path contains[ca.crt,sdk.crt,sdk.key] # if sdk.sm-crypto is true, contains [gm] directory, and gm dir contains [gmca.crt,gmsdk.crt,gmsdk.key,gmensdk.crt,gmensdk.key] -sdk.cert-path=conf +sdk.cert-path=resources/conf # amop public key of pem and private key of p12 configuration -amop.pub-path=conf/amop/consumer_public_key.pem -amop.pri-path=conf/amop/consumer_private_key.p12 +amop.pub-path=resources/conf/amop/consumer_public_key.pem +amop.pri-path=resources/conf/amop/consumer_private_key.p12 amop.p12-password=123456 diff --git a/gradle.properties b/gradle.properties index 9f36acf0f..822079151 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,8 +1,8 @@ org.gradle.jvmargs='-Dfile.encoding=UTF-8' jdkTlsNamedGroups=secp256r1,secp256k1 -repoType=cn -signing.keyId= -signing.password= -signing.secretKeyRingFile= -sonatypeUsername= -sonatypePassword= \ No newline at end of file +repoType=zn +signing.keyId=62A32F80 +signing.password=weidentity@123 +signing.secretKeyRingFile=./secring.gpg +sonatypeUsername=tonychen +sonatypePassword=Abcd1234!@#$ \ No newline at end of file diff --git a/src/main/java/com/webank/weid/app/AppCommand.java b/src/main/java/com/webank/weid/app/AppCommand.java index 82a257c22..b367096d0 100644 --- a/src/main/java/com/webank/weid/app/AppCommand.java +++ b/src/main/java/com/webank/weid/app/AppCommand.java @@ -4,7 +4,7 @@ import com.webank.weid.constant.ErrorCode; import com.webank.weid.exception.InitWeb3jException; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.service.rpc.WeIdService; import com.webank.weid.service.impl.WeIdServiceImpl; import org.apache.commons.lang3.StringUtils; diff --git a/src/main/java/com/webank/weid/constant/DataDriverConstant.java b/src/main/java/com/webank/weid/constant/DataDriverConstant.java index a56b6ef56..48b5739bb 100644 --- a/src/main/java/com/webank/weid/constant/DataDriverConstant.java +++ b/src/main/java/com/webank/weid/constant/DataDriverConstant.java @@ -280,4 +280,25 @@ public final class DataDriverConstant { public static final String DOMAIN_RESOURCE_INFO = "domain.resourceInfo"; public static final String DOMAIN_WEID_AUTH = "domain.weIdAuth"; + + /** + * 本地运行所需表. + */ + + public static final String LOCAL_WEID_DOCUMENT = "local.weIdDocument"; + + public static final String LOCAL_CPT = "local.cpt"; + + public static final String LOCAL_POLICY = "local.policy"; + + public static final String LOCAL_PRESENTATION = "local.presentation"; + + public static final String LOCAL_ROLE = "local.role"; + + public static final String LOCAL_AUTHORITY_ISSUER = "local.authorityIssuer"; + + public static final String LOCAL_SPECIFIC_ISSUER = "local.specificIssuer"; + + public static final String LOCAL_EVIDENCE = "local.evidence"; + } \ No newline at end of file diff --git a/src/main/java/com/webank/weid/constant/WeIdConstant.java b/src/main/java/com/webank/weid/constant/WeIdConstant.java index b38277575..09c935243 100644 --- a/src/main/java/com/webank/weid/constant/WeIdConstant.java +++ b/src/main/java/com/webank/weid/constant/WeIdConstant.java @@ -263,6 +263,11 @@ public final class WeIdConstant { public static final Long RECOGNIZED_AUTHORITY_ISSUER_FLAG = 1L; + /* + * State file path for run local + */ + public static final String STATE_FILE_PATH = "output/local_state"; + public static enum PublicKeyType { SM2("SM2"), //RSA("RSA"), diff --git a/src/main/java/com/webank/weid/exception/DataTypeCastException.java b/src/main/java/com/webank/weid/exception/DataTypeCastException.java index 966de500c..fbc6e22df 100644 --- a/src/main/java/com/webank/weid/exception/DataTypeCastException.java +++ b/src/main/java/com/webank/weid/exception/DataTypeCastException.java @@ -2,7 +2,7 @@ package com.webank.weid.exception; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; /** * WeIdBase Exception. Base Exception for WeIdentity Project. diff --git a/src/main/java/com/webank/weid/exception/DatabaseException.java b/src/main/java/com/webank/weid/exception/DatabaseException.java index 1d46161f4..8b7162683 100644 --- a/src/main/java/com/webank/weid/exception/DatabaseException.java +++ b/src/main/java/com/webank/weid/exception/DatabaseException.java @@ -2,7 +2,7 @@ package com.webank.weid.exception; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; /** * Database Exception. Base Exception for WeIdentity Project. diff --git a/src/main/java/com/webank/weid/exception/InitWeb3jException.java b/src/main/java/com/webank/weid/exception/InitWeb3jException.java index c89deb6e9..0386af5b0 100644 --- a/src/main/java/com/webank/weid/exception/InitWeb3jException.java +++ b/src/main/java/com/webank/weid/exception/InitWeb3jException.java @@ -2,7 +2,7 @@ package com.webank.weid.exception; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; /** * InitWeb3sdk Exception. diff --git a/src/main/java/com/webank/weid/exception/LoadContractException.java b/src/main/java/com/webank/weid/exception/LoadContractException.java index 1b374cf08..8bbcf9e69 100644 --- a/src/main/java/com/webank/weid/exception/LoadContractException.java +++ b/src/main/java/com/webank/weid/exception/LoadContractException.java @@ -2,7 +2,7 @@ package com.webank.weid.exception; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; /** * Load Contract Exception. diff --git a/src/main/java/com/webank/weid/exception/PrivateKeyIllegalException.java b/src/main/java/com/webank/weid/exception/PrivateKeyIllegalException.java index a3c43ce08..5fc6e8567 100644 --- a/src/main/java/com/webank/weid/exception/PrivateKeyIllegalException.java +++ b/src/main/java/com/webank/weid/exception/PrivateKeyIllegalException.java @@ -2,7 +2,7 @@ package com.webank.weid.exception; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; /** * Private Key IllegalException. diff --git a/src/main/java/com/webank/weid/exception/WeIdBaseException.java b/src/main/java/com/webank/weid/exception/WeIdBaseException.java index 396a39c67..98562e996 100644 --- a/src/main/java/com/webank/weid/exception/WeIdBaseException.java +++ b/src/main/java/com/webank/weid/exception/WeIdBaseException.java @@ -2,7 +2,7 @@ package com.webank.weid.exception; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; /** * WeIdBase Exception. Base Exception for WeIdentity Project. diff --git a/src/main/java/com/webank/weid/protocol/base/AuthenticationProperty.java b/src/main/java/com/webank/weid/protocol/base/AuthenticationProperty.java index c06b47a67..081a42954 100644 --- a/src/main/java/com/webank/weid/protocol/base/AuthenticationProperty.java +++ b/src/main/java/com/webank/weid/protocol/base/AuthenticationProperty.java @@ -2,7 +2,7 @@ package com.webank.weid.protocol.base; -import com.webank.weid.blockchain.util.DataToolUtils; +import com.webank.weid.util.DataToolUtils; import com.webank.weid.util.Multibase.Multibase; import com.webank.weid.util.Multicodec.DecodedData; import com.webank.weid.util.Multicodec.MulticodecEncoder; diff --git a/src/main/java/com/webank/weid/protocol/base/Credential.java b/src/main/java/com/webank/weid/protocol/base/Credential.java index beff1469e..424d74323 100644 --- a/src/main/java/com/webank/weid/protocol/base/Credential.java +++ b/src/main/java/com/webank/weid/protocol/base/Credential.java @@ -7,7 +7,7 @@ import lombok.Data; import org.apache.commons.lang3.StringUtils; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.constant.ParamKeyConstant; import com.webank.weid.protocol.inf.Hashable; import com.webank.weid.util.CredentialUtils; diff --git a/src/main/java/com/webank/weid/protocol/base/CredentialPojo.java b/src/main/java/com/webank/weid/protocol/base/CredentialPojo.java index cb1071837..8727b329f 100644 --- a/src/main/java/com/webank/weid/protocol/base/CredentialPojo.java +++ b/src/main/java/com/webank/weid/protocol/base/CredentialPojo.java @@ -14,7 +14,7 @@ import com.webank.weid.constant.CredentialConstant; import com.webank.weid.constant.CredentialType; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.constant.ParamKeyConstant; import com.webank.weid.exception.DataTypeCastException; import com.webank.weid.protocol.inf.Hashable; diff --git a/src/main/java/com/webank/weid/protocol/base/CredentialWrapper.java b/src/main/java/com/webank/weid/protocol/base/CredentialWrapper.java index 1fa85d266..0572571cd 100644 --- a/src/main/java/com/webank/weid/protocol/base/CredentialWrapper.java +++ b/src/main/java/com/webank/weid/protocol/base/CredentialWrapper.java @@ -7,7 +7,7 @@ import lombok.Data; import org.apache.commons.lang3.StringUtils; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.protocol.inf.Hashable; import com.webank.weid.util.CredentialUtils; diff --git a/src/main/java/com/webank/weid/protocol/base/GlobalStatus.java b/src/main/java/com/webank/weid/protocol/base/GlobalStatus.java new file mode 100644 index 000000000..472f6a64e --- /dev/null +++ b/src/main/java/com/webank/weid/protocol/base/GlobalStatus.java @@ -0,0 +1,71 @@ +package com.webank.weid.protocol.base; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.webank.weid.blockchain.protocol.inf.JsonSerializer; +import com.webank.weid.contract.deploy.AddressProcess; +import lombok.Data; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + + +/** + * The class of global status for running locally with database. + * + * @author afeexian + */ +@Data +public class GlobalStatus implements JsonSerializer { + + private static final Logger logger = LoggerFactory.getLogger(GlobalStatus.class); + + private int authority_issuer_current_cpt_id = 1000; + + private int none_authority_issuer_current_cpt_id = 2000000; + + private int authority_issuer_current_policy_id = 1000; + + private int none_authority_issuer_current_policy_id = 2000000; + + private int presentationId = 1; + + //TODO:给文件加锁 + public static void storeStatusToFile(GlobalStatus globalStatus, String fileName) { + try { + ObjectMapper mapper = new ObjectMapper(); + File file = new File(fileName); + // if file does not exists, then create it + if (!file.exists()) { + file.createNewFile(); + } + mapper.writeValue(file, globalStatus); + } catch (IOException e) { + logger.error("writer file exception", e); + } + } + + public static GlobalStatus readStatusFromFile(String fileName) { + try { + ObjectMapper mapper = new ObjectMapper(); + File file = new File(fileName); + // if file does not exists, then create it + if (file.exists()) { + return mapper.readValue(file, GlobalStatus.class); + } + file.createNewFile(); + return new GlobalStatus(); + } catch (IOException e) { + logger.error("writer file exception", e); + } + logger.error("readStatusFromFile() the {} does not exists.", fileName); + return null; + } +} diff --git a/src/main/java/com/webank/weid/protocol/base/PresentationE.java b/src/main/java/com/webank/weid/protocol/base/PresentationE.java index f13ac14e8..049459b57 100644 --- a/src/main/java/com/webank/weid/protocol/base/PresentationE.java +++ b/src/main/java/com/webank/weid/protocol/base/PresentationE.java @@ -2,7 +2,7 @@ package com.webank.weid.protocol.base; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.constant.ParamKeyConstant; import com.webank.weid.exception.DataTypeCastException; import com.webank.weid.protocol.inf.IProof; diff --git a/src/main/java/com/webank/weid/protocol/base/WeIdAuthentication.java b/src/main/java/com/webank/weid/protocol/base/WeIdAuthentication.java index 855a1ed6d..1f9e58294 100644 --- a/src/main/java/com/webank/weid/protocol/base/WeIdAuthentication.java +++ b/src/main/java/com/webank/weid/protocol/base/WeIdAuthentication.java @@ -7,7 +7,7 @@ /** * The base data structure to handle WeIdentity DID authority info. * - * @author darwindu + * @author afeexian */ @Data public class WeIdAuthentication { diff --git a/src/main/java/com/webank/weid/service/impl/AuthorityIssuerServiceImpl.java b/src/main/java/com/webank/weid/service/impl/AuthorityIssuerServiceImpl.java index efe1d2775..ceaf7071f 100644 --- a/src/main/java/com/webank/weid/service/impl/AuthorityIssuerServiceImpl.java +++ b/src/main/java/com/webank/weid/service/impl/AuthorityIssuerServiceImpl.java @@ -7,12 +7,16 @@ import java.util.ArrayList; import java.util.List; +import com.webank.weid.service.local.AuthorityIssuerServiceLocal; +import com.webank.weid.service.local.CptServiceLocal; +import com.webank.weid.service.local.PolicyServiceLocal; +import com.webank.weid.util.PropertyUtils; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.constant.WeIdConstant; import com.webank.weid.protocol.base.AuthorityIssuer; import com.webank.weid.protocol.base.IssuerType; @@ -20,7 +24,7 @@ import com.webank.weid.protocol.base.WeIdPrivateKey; 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.blockchain.protocol.response.ResponseData; import com.webank.weid.service.rpc.AuthorityIssuerService; import com.webank.weid.service.rpc.WeIdService; import com.webank.weid.util.WeIdUtils; @@ -34,10 +38,28 @@ public class AuthorityIssuerServiceImpl implements AuthorityIssuerService { private static final Logger logger = LoggerFactory .getLogger(AuthorityIssuerServiceImpl.class); - private static final com.webank.weid.blockchain.service.impl.AuthorityIssuerServiceImpl authorityBlockchainService = new com.webank.weid.blockchain.service.impl.AuthorityIssuerServiceImpl(); + private static com.webank.weid.blockchain.rpc.AuthorityIssuerService authorityBlockchainService; private WeIdService weIdService = new WeIdServiceImpl(); + public AuthorityIssuerServiceImpl(){ + authorityBlockchainService = getAuthorityIssuerService(); + } + + private static com.webank.weid.blockchain.rpc.AuthorityIssuerService getAuthorityIssuerService() { + if(authorityBlockchainService != null) { + return authorityBlockchainService; + } else { + String type = PropertyUtils.getProperty("deploy.style"); + if (type.equals("blockchain")) { + return new com.webank.weid.blockchain.service.impl.AuthorityIssuerServiceImpl(); + } else { + // default database + return new AuthorityIssuerServiceLocal(); + } + } + } + /** * Register a new Authority Issuer on Chain. * 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 d2a114517..72496f699 100644 --- a/src/main/java/com/webank/weid/service/impl/CptServiceImpl.java +++ b/src/main/java/com/webank/weid/service/impl/CptServiceImpl.java @@ -11,6 +11,8 @@ import com.webank.wedpr.selectivedisclosure.IssuerResult; import com.webank.weid.constant.DataDriverConstant; import com.webank.weid.exception.DatabaseException; +import com.webank.weid.service.local.CptServiceLocal; +import com.webank.weid.service.local.WeIdServiceLocal; import com.webank.weid.suite.persistence.PersistenceFactory; import com.webank.weid.suite.persistence.Persistence; import com.webank.weid.suite.persistence.PersistenceType; @@ -19,7 +21,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.constant.WeIdConstant; import com.webank.weid.protocol.base.Cpt; import com.webank.weid.protocol.base.CptBaseInfo; @@ -27,7 +29,7 @@ import com.webank.weid.protocol.base.WeIdPrivateKey; import com.webank.weid.protocol.request.CptMapArgs; import com.webank.weid.protocol.request.CptStringArgs; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.protocol.response.RsvSignature; import com.webank.weid.service.rpc.CptService; import com.webank.weid.suite.cache.CacheManager; @@ -41,7 +43,7 @@ public class CptServiceImpl implements CptService { private static final Logger logger = LoggerFactory.getLogger(CptServiceImpl.class); - private static final com.webank.weid.blockchain.service.impl.CptServiceImpl cptBlockchainService = new com.webank.weid.blockchain.service.impl.CptServiceImpl(); + private static com.webank.weid.blockchain.rpc.CptService cptBlockchainService; private static Persistence dataDriver; private static PersistenceType persistenceType; @@ -49,6 +51,24 @@ public class CptServiceImpl implements CptService { private static CacheNode> cptCahceNode = CacheManager.registerCacheNode("SYS_CPT", 1000 * 3600 * 24L); + public CptServiceImpl(){ + cptBlockchainService = getCptService(); + } + + private static com.webank.weid.blockchain.rpc.CptService getCptService() { + if(cptBlockchainService != null) { + return cptBlockchainService; + } else { + String type = PropertyUtils.getProperty("deploy.style"); + if (type.equals("blockchain")) { + return new com.webank.weid.blockchain.service.impl.CptServiceImpl(); + } else { + // default database + return new CptServiceLocal(); + } + } + } + /** * Register a new CPT with a pre-set CPT ID, to the blockchain. * 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 44ab464d2..183a8424b 100644 --- a/src/main/java/com/webank/weid/service/impl/CredentialPojoServiceImpl.java +++ b/src/main/java/com/webank/weid/service/impl/CredentialPojoServiceImpl.java @@ -14,7 +14,8 @@ import com.webank.weid.protocol.cpt.Cpt101; import com.webank.weid.protocol.cpt.Cpt111; import com.webank.weid.protocol.request.CreateCredentialPojoArgs; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.constant.ErrorCode; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.service.rpc.CptService; import com.webank.weid.service.rpc.CredentialPojoService; import com.webank.weid.service.rpc.WeIdService; 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 d83876ba1..d7ee9a0cd 100644 --- a/src/main/java/com/webank/weid/service/impl/CredentialServiceImpl.java +++ b/src/main/java/com/webank/weid/service/impl/CredentialServiceImpl.java @@ -4,12 +4,12 @@ import com.networknt.schema.ValidationMessage; import com.webank.weid.constant.CredentialConstant; import com.webank.weid.constant.CredentialFieldDisclosureValue; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.constant.ParamKeyConstant; import com.webank.weid.exception.WeIdBaseException; import com.webank.weid.protocol.base.*; import com.webank.weid.protocol.request.CreateCredentialArgs; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.service.rpc.CptService; import com.webank.weid.service.rpc.CredentialService; import com.webank.weid.service.rpc.WeIdService; 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 03a283dd0..17329f9ac 100644 --- a/src/main/java/com/webank/weid/service/impl/EvidenceServiceImpl.java +++ b/src/main/java/com/webank/weid/service/impl/EvidenceServiceImpl.java @@ -6,14 +6,16 @@ import com.google.common.io.Files; +import com.webank.weid.service.local.EvidenceServiceLocal; +import com.webank.weid.service.local.WeIdServiceLocal; import com.webank.weid.service.rpc.EvidenceService; import com.webank.weid.service.rpc.WeIdService; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.constant.ProcessingMode; import com.webank.weid.constant.WeIdConstant; import com.webank.weid.protocol.base.*; import com.webank.weid.protocol.inf.Hashable; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.util.*; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; @@ -40,14 +42,32 @@ public class EvidenceServiceImpl implements EvidenceService { //private EvidenceServiceEngine evidenceServiceEngine; - private static com.webank.weid.blockchain.service.impl.EvidenceServiceImpl evidenceBlockchainService; + private static com.webank.weid.blockchain.rpc.EvidenceService evidenceBlockchainService; //private String groupId; public EvidenceServiceImpl() { //super(); //initEvidenceServiceEngine(masterGroupId); - evidenceBlockchainService = new com.webank.weid.blockchain.service.impl.EvidenceServiceImpl(); + evidenceBlockchainService = getEvidenceService(StringUtils.EMPTY); + } + + private static com.webank.weid.blockchain.rpc.EvidenceService getEvidenceService(String groupId) { + if(evidenceBlockchainService != null) { + return evidenceBlockchainService; + } else { + String type = PropertyUtils.getProperty("deploy.style"); + if (type.equals("blockchain")) { + if(!groupId.equals(StringUtils.EMPTY)) { + return new com.webank.weid.blockchain.service.impl.EvidenceServiceImpl(groupId); + } else { + return new com.webank.weid.blockchain.service.impl.EvidenceServiceImpl(); + } + } else { + // default database + return new EvidenceServiceLocal(); + } + } } /** @@ -60,7 +80,7 @@ public EvidenceServiceImpl(ProcessingMode processingMode, String groupId) { //super(groupId); this.processingMode = processingMode; //initEvidenceServiceEngine(groupId); - evidenceBlockchainService = new com.webank.weid.blockchain.service.impl.EvidenceServiceImpl(groupId); + evidenceBlockchainService = getEvidenceService(groupId); } /*private void initEvidenceServiceEngine(String groupId) { @@ -165,7 +185,7 @@ public ResponseData createEvidence(Hashable object, WeIdPrivateKey weIdP return new ResponseData<>(StringUtils.EMPTY, ErrorCode.WEID_PRIVATEKEY_INVALID); } return hashToNewEvidence(hashResp.getResult(), weIdPrivateKey.getPrivateKey(), - StringUtils.EMPTY); + "empty log"); } /** @@ -507,14 +527,14 @@ private ResponseData hashToNewEvidence(String hashValue, String privateK args[2] = extra; args[3] = String.valueOf(timestamp); args[4] = privateKey; - args[5] = String.valueOf(evidenceBlockchainService.groupId); + args[5] = String.valueOf(evidenceBlockchainService.getGroupId()); String rawData = new StringBuffer() .append(hashValue) .append(signature) .append(extra) .append(timestamp) .append(WeIdUtils.getWeIdFromPrivateKey(privateKey)) - .append(evidenceBlockchainService.groupId).toString(); + .append(evidenceBlockchainService.getGroupId()).toString(); //替换国密 String hash = DataToolUtils.hash(rawData); String requestId = new BigInteger(hash.substring(2), 16).toString(); @@ -763,7 +783,7 @@ public ResponseData createEvidenceWithLogAndCustomKey( args[3] = String.valueOf(timestamp); args[4] = customKey; args[5] = privateKey; - args[6] = String.valueOf(evidenceBlockchainService.groupId); + args[6] = String.valueOf(evidenceBlockchainService.getGroupId()); String rawData = new StringBuffer() .append(hashValue) .append(signature) @@ -771,7 +791,7 @@ public ResponseData createEvidenceWithLogAndCustomKey( .append(timestamp) .append(customKey) .append(WeIdUtils.getWeIdFromPrivateKey(privateKey)) - .append(evidenceBlockchainService.groupId).toString(); + .append(evidenceBlockchainService.getGroupId()).toString(); String hash = DataToolUtils.hash(rawData); String requestId = new BigInteger(hash.substring(2), 16).toString(); boolean isSuccess = BatchTransactionUtils diff --git a/src/main/java/com/webank/weid/service/impl/PolicyServiceImpl.java b/src/main/java/com/webank/weid/service/impl/PolicyServiceImpl.java index d7e640189..4b252a03d 100644 --- a/src/main/java/com/webank/weid/service/impl/PolicyServiceImpl.java +++ b/src/main/java/com/webank/weid/service/impl/PolicyServiceImpl.java @@ -5,18 +5,21 @@ import java.util.List; import java.util.Map; +import com.webank.weid.service.local.PolicyServiceLocal; +import com.webank.weid.service.local.WeIdServiceLocal; +import com.webank.weid.util.PropertyUtils; import org.apache.commons.collections4.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.constant.WeIdConstant; import com.webank.weid.protocol.base.ClaimPolicy; import com.webank.weid.protocol.base.PresentationPolicyE; import com.webank.weid.protocol.base.WeIdAuthentication; import com.webank.weid.protocol.base.WeIdPrivateKey; import com.webank.weid.protocol.request.CptMapArgs; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.protocol.response.RsvSignature; import com.webank.weid.service.rpc.PolicyService; import com.webank.weid.util.CredentialPojoUtils; @@ -32,8 +35,25 @@ public class PolicyServiceImpl implements PolicyService { private static final Logger logger = LoggerFactory.getLogger(PolicyServiceImpl.class); - private static final com.webank.weid.blockchain.service.impl.PolicyServiceImpl policyBlockchainService = new com.webank.weid.blockchain.service.impl.PolicyServiceImpl(); + private static com.webank.weid.blockchain.rpc.PolicyService policyBlockchainService; + public PolicyServiceImpl(){ + policyBlockchainService = getPolicyService(); + } + + private static com.webank.weid.blockchain.rpc.PolicyService getPolicyService() { + if(policyBlockchainService != null) { + return policyBlockchainService; + } else { + String type = PropertyUtils.getProperty("deploy.style"); + if (type.equals("blockchain")) { + return new com.webank.weid.blockchain.service.impl.PolicyServiceImpl(); + } else { + // default database + return new PolicyServiceLocal(); + } + } + } /** * Register Claim Policy on blockchain and assign it under a CPT ID. * 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 7a38fe2bc..81af7978c 100644 --- a/src/main/java/com/webank/weid/service/impl/WeIdServiceImpl.java +++ b/src/main/java/com/webank/weid/service/impl/WeIdServiceImpl.java @@ -3,32 +3,40 @@ package com.webank.weid.service.impl; import com.fasterxml.jackson.databind.ObjectMapper; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.constant.WeIdConstant; import com.webank.weid.protocol.base.*; import com.webank.weid.protocol.request.AuthenticationArgs; import com.webank.weid.protocol.request.CreateWeIdArgs; import com.webank.weid.protocol.request.ServiceArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.protocol.response.WeIdListResult; +import com.webank.weid.service.local.WeIdServiceLocal; import com.webank.weid.service.rpc.WeIdService; +import com.webank.weid.suite.persistence.Persistence; +import com.webank.weid.suite.persistence.PersistenceFactory; +import com.webank.weid.suite.persistence.PersistenceType; import com.webank.weid.util.DataToolUtils; import com.webank.weid.util.Multibase.Multibase; import com.webank.weid.util.Multicodec.Multicodec; import com.webank.weid.util.Multicodec.MulticodecEncoder; +import com.webank.weid.util.PropertyUtils; import com.webank.weid.util.WeIdUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.fisco.bcos.sdk.model.CryptoType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Objects; +import java.util.Properties; /** * Service implementations for operations on WeIdentity DID. @@ -42,7 +50,25 @@ public class WeIdServiceImpl implements WeIdService { */ private static final Logger logger = LoggerFactory.getLogger(WeIdServiceImpl.class); - private static final com.webank.weid.blockchain.service.impl.WeIdServiceImpl weIdBlockchainService = new com.webank.weid.blockchain.service.impl.WeIdServiceImpl(); + private static com.webank.weid.blockchain.rpc.WeIdService weIdBlockchainService; + + public WeIdServiceImpl(){ + weIdBlockchainService = getWeIdService(); + } + + private static com.webank.weid.blockchain.rpc.WeIdService getWeIdService() { + if(weIdBlockchainService != null) { + return weIdBlockchainService; + } else { + String type = PropertyUtils.getProperty("deploy.style"); + if (type.equals("blockchain")) { + return new com.webank.weid.blockchain.service.impl.WeIdServiceImpl(); + } else { + // default database + return new WeIdServiceLocal(); + } + } + } /** * Create a WeIdentity DID with null input param. @@ -64,7 +90,7 @@ public ResponseData createWeId() { //verification method controller默认为自己 authenticationProperty.setController(result.getWeId()); //这里把publicKey用multicodec编码,然后使用Multibase格式化,国密和非国密使用不同的编码 - byte[] publicKeyEncode = MulticodecEncoder.encode(com.webank.weid.blockchain.util.DataToolUtils.cryptoType == CryptoType.ECDSA_TYPE? Multicodec.ED25519_PUB:Multicodec.SM2_PUB, + byte[] publicKeyEncode = MulticodecEncoder.encode(DataToolUtils.cryptoType == CryptoType.ECDSA_TYPE? Multicodec.ED25519_PUB:Multicodec.SM2_PUB, result.getUserWeIdPublicKey().getPublicKey().getBytes(StandardCharsets.UTF_8)); authenticationProperty.setPublicKeyMultibase(Multibase.encode(Multibase.Base.Base58BTC, publicKeyEncode)); List authList = new ArrayList<>(); @@ -117,7 +143,7 @@ public ResponseData createWeIdByPublicKey(WeIdPublicKey weIdPublicKey, W //verification method controller默认为自己 authenticationProperty.setController(weId); //这里把publicKey用multicodec编码,然后使用Multibase格式化,国密和非国密使用不同的编码 - byte[] publicKeyEncode = MulticodecEncoder.encode(com.webank.weid.blockchain.util.DataToolUtils.cryptoType == CryptoType.ECDSA_TYPE? Multicodec.ED25519_PUB:Multicodec.SM2_PUB, + byte[] publicKeyEncode = MulticodecEncoder.encode(DataToolUtils.cryptoType == CryptoType.ECDSA_TYPE? Multicodec.ED25519_PUB:Multicodec.SM2_PUB, publicKey.getBytes(StandardCharsets.UTF_8)); authenticationProperty.setPublicKeyMultibase(Multibase.encode(Multibase.Base.Base58BTC, publicKeyEncode)); List authList = new ArrayList<>(); @@ -188,7 +214,7 @@ public ResponseData createWeId(CreateWeIdArgs createWeIdArgs) { //verification method controller默认为自己 authenticationProperty.setController(weId); //这里把publicKey用multicodec编码,然后使用Multibase格式化,国密和非国密使用不同的编码 - byte[] publicKeyEncode = MulticodecEncoder.encode(com.webank.weid.blockchain.util.DataToolUtils.cryptoType == CryptoType.ECDSA_TYPE? Multicodec.ED25519_PUB:Multicodec.SM2_PUB, + byte[] publicKeyEncode = MulticodecEncoder.encode(DataToolUtils.cryptoType == CryptoType.ECDSA_TYPE? Multicodec.ED25519_PUB:Multicodec.SM2_PUB, publicKey.getBytes(StandardCharsets.UTF_8)); authenticationProperty.setPublicKeyMultibase(Multibase.encode(Multibase.Base.Base58BTC, publicKeyEncode)); List authList = new ArrayList<>(); @@ -234,7 +260,7 @@ public ResponseData getWeIdDocument(String weId) { } com.webank.weid.blockchain.protocol.response.ResponseData innerResp = weIdBlockchainService.getWeIdDocument(weId); //ResponseData weIdDocResp = weIdServiceEngine.getWeIdDocument(weId); - if(innerResp.getErrorCode() == ErrorCode.SUCCESS.getCode()){ + if(innerResp.getErrorCode() == ErrorCode.SUCCESS.getCode() && innerResp.getResult() != null){ WeIdDocument weIdDocument = WeIdDocument.fromBlockChain(innerResp.getResult()); return new ResponseData<>(weIdDocument, ErrorCode.SUCCESS); } else { @@ -461,7 +487,7 @@ private ResponseData processSetAuthentication( authenticationProperty.setId(weId + "#keys-" + DataToolUtils.hash(authenticationArgs.getPublicKey()).substring(58)); } authenticationProperty.setController(authenticationArgs.getController()); - byte[] publicKeyEncode = MulticodecEncoder.encode(com.webank.weid.blockchain.util.DataToolUtils.cryptoType == CryptoType.ECDSA_TYPE? Multicodec.ED25519_PUB:Multicodec.SM2_PUB, + byte[] publicKeyEncode = MulticodecEncoder.encode(DataToolUtils.cryptoType == CryptoType.ECDSA_TYPE? Multicodec.ED25519_PUB:Multicodec.SM2_PUB, authenticationArgs.getPublicKey().getBytes(StandardCharsets.UTF_8)); authenticationProperty.setPublicKeyMultibase(Multibase.encode(Multibase.Base.Base58BTC, publicKeyEncode)); @@ -528,7 +554,6 @@ public ResponseData revokeAuthentication( logger.error("[revokeAuthentication]: failed, the weid :{} does not exist", weId); return new ResponseData<>(false, ErrorCode.WEID_DOES_NOT_EXIST); } - String weAddress = WeIdUtils.convertWeIdToAddress(weId); WeIdDocument weIdDocument = this.getWeIdDocument(weId).getResult(); List authentication = weIdDocument.getAuthentication(); if(!StringUtils.isEmpty(authenticationArgs.getPublicKey())){ diff --git a/src/main/java/com/webank/weid/service/local/AuthorityIssuerServiceLocal.java b/src/main/java/com/webank/weid/service/local/AuthorityIssuerServiceLocal.java new file mode 100644 index 000000000..e73c41727 --- /dev/null +++ b/src/main/java/com/webank/weid/service/local/AuthorityIssuerServiceLocal.java @@ -0,0 +1,581 @@ +package com.webank.weid.service.local; + +import com.webank.weid.blockchain.constant.ChainType; +import com.webank.weid.blockchain.constant.ErrorCode; +import com.webank.weid.blockchain.constant.WeIdConstant; +import com.webank.weid.blockchain.protocol.base.AuthorityIssuer; +import com.webank.weid.blockchain.protocol.base.CptBaseInfo; +import com.webank.weid.blockchain.protocol.base.IssuerType; +import com.webank.weid.blockchain.protocol.request.RegisterAuthorityIssuerArgs; +import com.webank.weid.blockchain.protocol.response.ResponseData; +import com.webank.weid.blockchain.rpc.AuthorityIssuerService; +import com.webank.weid.blockchain.service.impl.AuthorityIssuerServiceImpl; +import com.webank.weid.blockchain.util.DataToolUtils; +import com.webank.weid.util.WeIdUtils; +import com.webank.weid.constant.DataDriverConstant; +import com.webank.weid.contract.deploy.AddressProcess; +import com.webank.weid.exception.DatabaseException; +import com.webank.weid.exception.WeIdBaseException; +import com.webank.weid.service.local.role.RoleController; +import com.webank.weid.suite.persistence.*; +import com.webank.weid.suite.persistence.mysql.SqlDomain; +import com.webank.weid.suite.persistence.mysql.SqlExecutor; +import com.webank.weid.util.PropertyUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.io.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +@Component("authorityIssuerServiceLocal") +public class AuthorityIssuerServiceLocal implements AuthorityIssuerService { + private static final Logger logger = LoggerFactory.getLogger(AuthorityIssuerServiceLocal.class); + + private static Persistence dataDriver; + private static PersistenceType persistenceType; + WeIdServiceLocal weIdServiceLocal = new WeIdServiceLocal(); + RoleController roleController = new RoleController(); + + private static 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; + } + + /** + * add a new Authority Issuer on Chain. + * + * @param args the args + * @return the Boolean response data + */ + @Override + public ResponseData addAuthorityIssuer(RegisterAuthorityIssuerArgs args) { + AuthorityIssuer authorityIssuer = args.getAuthorityIssuer(); + if(!com.webank.weid.blockchain.util.WeIdUtils.isPrivateKeyValid(args.getWeIdPrivateKey())){ + logger.error("[addAuthorityIssuer] the privateKey of issuer is not valid"); + return new ResponseData<>(false, ErrorCode.AUTHORITY_ISSUER_ERROR); + } + //如果不存在该weId则报错 + if(!weIdServiceLocal.isWeIdExist(authorityIssuer.getWeId()).getResult()){ + logger.error("[addAuthorityIssuer] the weid of authority does not exist on blockchain"); + return new ResponseData<>(false, ErrorCode.WEID_DOES_NOT_EXIST); + } + if(getDataDriver().getAuthorityIssuerByWeId(DataDriverConstant.LOCAL_AUTHORITY_ISSUER, authorityIssuer.getWeId()).getResult() != null){ + logger.error("[addAuthorityIssuer] Authority Issuer already exist"); + return new ResponseData<>(false, ErrorCode.AUTHORITY_ISSUER_CONTRACT_ERROR_ALREADY_EXIST); + } + if(getDataDriver().getAuthorityIssuerByName(DataDriverConstant.LOCAL_AUTHORITY_ISSUER, authorityIssuer.getName()).getResult() != null){ + logger.error("[addAuthorityIssuer] Authority Issuer's name already exist"); + return new ResponseData<>(false, ErrorCode.AUTHORITY_ISSUER_CONTRACT_ERROR_NAME_ALREADY_EXISTS); + } + String extraStr = null; + if(authorityIssuer.getExtraStr32().size() != 0){ + extraStr = authorityIssuer.getExtraStr32().get(0); + if(authorityIssuer.getExtraStr32().size() > 1) { + for(int i = 1; i < authorityIssuer.getExtraStr32().size(); i++){ + extraStr = extraStr + ',' + authorityIssuer.getExtraStr32().get(i); + } + } + } + String extraInt = null; + if(authorityIssuer.getExtraInt().size() != 0) { + extraInt = String.valueOf(authorityIssuer.getExtraInt().get(0)); + if (authorityIssuer.getExtraInt().size() > 1) { + for (int i = 1; i < authorityIssuer.getExtraInt().size(); i++) { + extraInt = extraInt + ',' + authorityIssuer.getExtraInt().get(i); + } + } + } + ResponseData resp = + getDataDriver().addAuthorityIssuer( + DataDriverConstant.LOCAL_AUTHORITY_ISSUER, + authorityIssuer.getWeId(), + authorityIssuer.getName(), + authorityIssuer.getDescription(), + authorityIssuer.getAccValue(), + extraStr, + extraInt + ); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[addAuthorityIssuer] save addAuthorityIssuer to db failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(true, ErrorCode.SUCCESS); + } + + /** + * Remove a new Authority Issuer on Chain. + * + * @param weId the weId + * @param privateKey the privateKey + * @return the Boolean response data + */ + @Override + public ResponseData removeAuthorityIssuer(String weId, String privateKey) { + if(!RoleController.checkPermission(WeIdUtils.getWeIdFromPrivateKey(privateKey), RoleController.MODIFY_AUTHORITY_ISSUER)){ + logger.error("[removeAuthorityIssuer] operator has not permission to removeAuthorityIssuer"); + return new ResponseData<>(false, ErrorCode.CONTRACT_ERROR_NO_PERMISSION); + } + if(getDataDriver().getAuthorityIssuerByWeId(DataDriverConstant.LOCAL_AUTHORITY_ISSUER, weId).getResult() == null){ + logger.error("[removeAuthorityIssuer] Authority Issuer not exist"); + return new ResponseData<>(false, ErrorCode.AUTHORITY_ISSUER_CONTRACT_ERROR_NOT_EXISTS); + } + if(roleController.checkRole(weId, RoleController.ROLE_AUTHORITY_ISSUER) && !roleController.removeRole(WeIdUtils.getWeIdFromPrivateKey(privateKey), weId, RoleController.ROLE_AUTHORITY_ISSUER)) { + logger.error("[removeAuthorityIssuer] remove AuthorityIssuer role from db failed."); + return new ResponseData<>(false, ErrorCode.AUTHORITY_ISSUER_ERROR); + } + ResponseData resp = + getDataDriver().removeAuthorityIssuer( + DataDriverConstant.LOCAL_AUTHORITY_ISSUER, + weId); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[removeAuthorityIssuer] delete addAuthorityIssuer from db failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(true, ErrorCode.SUCCESS); + } + + /** + * Check whether the given weId is an authority issuer. + * + * @param addr the address of WeIdentity DID + * @return the Boolean response data + */ + @Override + public ResponseData isAuthorityIssuer(String addr) { + if(!RoleController.checkRole(WeIdUtils.convertAddressToWeId(addr), RoleController.ROLE_AUTHORITY_ISSUER)){ + return new ResponseData<>(false, ErrorCode.SUCCESS); + } + if(getDataDriver().getAuthorityIssuerByWeId(DataDriverConstant.LOCAL_AUTHORITY_ISSUER, WeIdUtils.convertAddressToWeId(addr)).getResult() == null){ + return new ResponseData<>(false, ErrorCode.SUCCESS); + } + return new ResponseData<>(true, ErrorCode.SUCCESS); + } + + /** + * Recognize this WeID to be an authority issuer. + * + * @param stage the stage that weather recognize + * @param addr the address of WeIdentity DID + * @param privateKey the private key set + * @return true if succeeds, false otherwise + */ + @Override + public ResponseData recognizeWeId(Boolean stage, String addr, String privateKey) { + if(!RoleController.checkPermission(WeIdUtils.getWeIdFromPrivateKey(privateKey), RoleController.MODIFY_AUTHORITY_ISSUER)){ + logger.error("[recognizeWeId] operator has not permission to recognizeWeId"); + return new ResponseData<>(false, ErrorCode.CONTRACT_ERROR_NO_PERMISSION); + } + if(getDataDriver().getAuthorityIssuerByWeId(DataDriverConstant.LOCAL_AUTHORITY_ISSUER, WeIdUtils.convertAddressToWeId(addr)).getResult() == null){ + logger.error("[recognizeWeId] Authority Issuer not exist"); + return new ResponseData<>(false, ErrorCode.AUTHORITY_ISSUER_CONTRACT_ERROR_NOT_EXISTS); + } + if(stage){ + if(!roleController.addRole(WeIdUtils.getWeIdFromPrivateKey(privateKey), WeIdUtils.convertAddressToWeId(addr), RoleController.ROLE_AUTHORITY_ISSUER)){ + logger.error("[recognizeWeId] add AuthorityIssuer role to db failed."); + return new ResponseData<>(false, ErrorCode.AUTHORITY_ISSUER_ERROR); + } + ResponseData resp = getDataDriver().updateAuthorityIssuer(DataDriverConstant.LOCAL_AUTHORITY_ISSUER, WeIdUtils.convertAddressToWeId(addr), 1); + if(resp.getErrorCode() != ErrorCode.SUCCESS.getCode()){ + logger.error("[recognizeWeId] update AuthorityIssuer recognize to db failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(true, ErrorCode.SUCCESS); + } else { + if(!roleController.removeRole(WeIdUtils.getWeIdFromPrivateKey(privateKey), WeIdUtils.convertAddressToWeId(addr), RoleController.ROLE_AUTHORITY_ISSUER)){ + logger.error("[recognizeWeId] remove AuthorityIssuer role from db failed."); + return new ResponseData<>(false, ErrorCode.AUTHORITY_ISSUER_ERROR); + } + ResponseData resp = getDataDriver().updateAuthorityIssuer(DataDriverConstant.LOCAL_AUTHORITY_ISSUER, WeIdUtils.convertAddressToWeId(addr), 0); + if(resp.getErrorCode() != ErrorCode.SUCCESS.getCode()){ + logger.error("[recognizeWeId] update AuthorityIssuer deRecognize to db failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(true, ErrorCode.SUCCESS); + } + } + + /** + * Query the authority issuer information given weId. + * + * @param weId the WeIdentity DID + * @return the AuthorityIssuer response data + */ + @Override + public ResponseData queryAuthorityIssuerInfo(String weId) { + ResponseData resultData = new ResponseData(); + AuthorityIssuer result = new AuthorityIssuer(); + AuthorityIssuerInfo authorityIssuerInfo = getDataDriver().getAuthorityIssuerByWeId(DataDriverConstant.LOCAL_AUTHORITY_ISSUER, weId).getResult(); + if(authorityIssuerInfo == null){ + logger.error("[queryAuthorityIssuerInfo] Authority Issuer not exist"); + return new ResponseData<>(null, ErrorCode.AUTHORITY_ISSUER_CONTRACT_ERROR_NOT_EXISTS); + } + result.setWeId(weId); + result.setName(authorityIssuerInfo.getName()); + result.setAccValue(authorityIssuerInfo.getAcc_value()); + result.setCreated(authorityIssuerInfo.getCreated().getTime()); + result.setDescription(authorityIssuerInfo.getDescription()); + result.setRecognized(authorityIssuerInfo.getRecognize()==1); + if(authorityIssuerInfo.getExtra_str() != null){ + result.setExtraStr32(Arrays.asList(authorityIssuerInfo.getExtra_str().split(","))); + } + if(authorityIssuerInfo.getExtra_int() != null){ + List extraInt = new ArrayList<>(); + for(String i:authorityIssuerInfo.getExtra_int().split(",")){ + extraInt.add(Integer.valueOf(i)); + } + result.setExtraInt(extraInt); + } + resultData.setResult(result); + return resultData; + } + + /** + * Get all of the authority issuer. + * + * @param index start position + * @param num number of returned authority issuer in this request + * @return Execution result + */ + @Override + public ResponseData> getAuthorityIssuerAddressList(Integer index, Integer num) { + try { + return getDataDriver().getWeIdList( + DataDriverConstant.LOCAL_AUTHORITY_ISSUER, + index, + index + num); + } catch (Exception e) { + logger.error("[getAuthorityIssuerAddressList] getAuthorityIssuerAddressList has error, Error Message:{}", e); + return new ResponseData<>(null, ErrorCode.PERSISTENCE_EXECUTE_FAILED); + } + } + + /** + * Register a new issuer type. + * + * @param privateKey the caller + * @param issuerType the specified issuer type + * @return Execution result + */ + @Override + public ResponseData registerIssuerType( + String privateKey, + String issuerType + ) { + if (StringUtils.isEmpty(issuerType) || StringUtils.isEmpty(privateKey)) { + logger.error("[registerIssuerType] input argument is illegal"); + return new ResponseData<>(false, ErrorCode.ILLEGAL_INPUT); + } + if(getDataDriver().getSpecificType(DataDriverConstant.LOCAL_SPECIFIC_ISSUER, issuerType).getResult() != null){ + logger.error("[registerIssuerType] issuerType already exist on chain"); + return new ResponseData<>(false, ErrorCode.SPECIFIC_ISSUER_CONTRACT_ERROR_ALREADY_EXISTS); + } + ResponseData resp = + getDataDriver().addSpecificType( + DataDriverConstant.LOCAL_SPECIFIC_ISSUER, + issuerType, + WeIdUtils.getWeIdFromPrivateKey(privateKey)); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[registerIssuerType] save IssuerType to db failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(true, ErrorCode.SUCCESS); + } + + /** + * Marked an issuer as the specified issuer type. + * + * @param privateKey the caller who have the access to modify this list + * @param issuerType the specified issuer type + * @param issuerAddress the address of the issuer who will be marked as a specific issuer type + * @return Execution result + */ + @Override + public ResponseData addIssuer( + String privateKey, + String issuerType, + String issuerAddress + ) { + if (StringUtils.isEmpty(issuerType) || StringUtils.isEmpty(issuerAddress) ||StringUtils.isEmpty(privateKey)) { + logger.error("[addIssuer] input argument is illegal"); + return new ResponseData<>(false, ErrorCode.ILLEGAL_INPUT); + } + if(!RoleController.checkPermission(WeIdUtils.getWeIdFromPrivateKey(privateKey), RoleController.MODIFY_KEY_CPT)){ + logger.error("[addIssuer] operator has not permission to addIssuer"); + return new ResponseData<>(false, ErrorCode.CONTRACT_ERROR_NO_PERMISSION); + } + SpecificTypeValue specificTypeValue = getDataDriver().getSpecificType(DataDriverConstant.LOCAL_SPECIFIC_ISSUER, issuerType).getResult(); + if(specificTypeValue == null){ + logger.error("[addIssuer] issuerType not exist on chain"); + return new ResponseData<>(false, ErrorCode.SPECIFIC_ISSUER_CONTRACT_ERROR_ALREADY_NOT_EXIST); + } + //判断这个issuerType是否已经有fellow + if(specificTypeValue.getFellow() != null){ + //判断是否已经存在这个issuer + String[] fellows = specificTypeValue.getFellow().split(","); + for (String obj : fellows) { + if(obj.equals(issuerAddress)) return new ResponseData<>(false, ErrorCode.SPECIFIC_ISSUER_CONTRACT_ERROR_ALREADY_EXISTS); + } + ResponseData resp = + getDataDriver().updateSpecificTypeFellow( + DataDriverConstant.LOCAL_SPECIFIC_ISSUER, + issuerType, + specificTypeValue.getFellow()+','+issuerAddress); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[addIssuer] addIssuer to issuerType failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(true, ErrorCode.SUCCESS); + } else { + ResponseData resp = + getDataDriver().updateSpecificTypeFellow( + DataDriverConstant.LOCAL_SPECIFIC_ISSUER, + issuerType, + issuerAddress); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[addIssuer] addIssuer to issuerType failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(true, ErrorCode.SUCCESS); + } + } + + /** + * Removed an issuer from the specified issuer list. + * + * @param privateKey the caller who have the access to modify this list + * @param issuerType the specified issuer type + * @param issuerAddress the address of the issuer who will be marked as a specific issuer type + * @return Execution result + */ + @Override + public ResponseData removeIssuer( + String privateKey, + String issuerType, + String issuerAddress + ) { + if (StringUtils.isEmpty(issuerType) || StringUtils.isEmpty(issuerAddress) ||StringUtils.isEmpty(privateKey)) { + logger.error("[removeIssuer] input argument is illegal"); + return new ResponseData<>(false, ErrorCode.ILLEGAL_INPUT); + } + if(!RoleController.checkPermission(WeIdUtils.getWeIdFromPrivateKey(privateKey), RoleController.MODIFY_KEY_CPT)){ + logger.error("[removeIssuer] operator has not permission to removeIssuer"); + return new ResponseData<>(false, ErrorCode.CONTRACT_ERROR_NO_PERMISSION); + } + SpecificTypeValue specificTypeValue = getDataDriver().getSpecificType(DataDriverConstant.LOCAL_SPECIFIC_ISSUER, issuerType).getResult(); + if(!isSpecificTypeIssuer(issuerType, issuerAddress).getResult()){ + logger.error("[removeIssuer] issuerAddress not the fellow of issuerType"); + return new ResponseData<>(false, ErrorCode.SPECIFIC_ISSUER_CONTRACT_ERROR_ALREADY_NOT_EXIST); + } + String[] fellows = specificTypeValue.getFellow().split(","); + List fellowList = new ArrayList<>(Arrays.asList(fellows)); + fellowList.remove(issuerAddress); + String newFellow = fellowList.get(0); + if(fellowList.size() != 1) { + for(int i = 1; i < fellowList.size(); i++){ + newFellow = newFellow + ',' + fellowList.get(i); + } + } + ResponseData resp = + getDataDriver().updateSpecificTypeFellow( + DataDriverConstant.LOCAL_SPECIFIC_ISSUER, + issuerType, + newFellow); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[removeIssuer] removeIssuer from issuerType failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(true, ErrorCode.SUCCESS); + } + + /** + * Check if the given WeId is belonging to a specific issuer type. + * + * @param issuerType the issuer type + * @param address the address + * @return true if yes, false otherwise + */ + @Override + public ResponseData isSpecificTypeIssuer( + String issuerType, + String address + ) { + if (StringUtils.isEmpty(issuerType) || StringUtils.isEmpty(address)) { + logger.error("[isSpecificTypeIssuer] input argument is illegal"); + return new ResponseData<>(false, ErrorCode.ILLEGAL_INPUT); + } + SpecificTypeValue specificTypeValue = getDataDriver().getSpecificType(DataDriverConstant.LOCAL_SPECIFIC_ISSUER, issuerType).getResult(); + if(specificTypeValue == null){ + logger.error("[isSpecificTypeIssuer] issuerType not exist on chain"); + return new ResponseData<>(false, ErrorCode.SPECIFIC_ISSUER_CONTRACT_ERROR_ALREADY_NOT_EXIST); + } + if(specificTypeValue.getFellow().equals(StringUtils.EMPTY)){ + logger.error("[isSpecificTypeIssuer] issuerType has not fellow"); + return new ResponseData<>(false, ErrorCode.SPECIFIC_ISSUER_CONTRACT_ERROR_ALREADY_NOT_EXIST); + } + String[] fellows = specificTypeValue.getFellow().split(","); + for (String obj : fellows) { + if(obj.equals(address)) return new ResponseData<>(true, ErrorCode.SUCCESS); + } + return new ResponseData<>(false, ErrorCode.SUCCESS); + } + + /** + * Get all specific typed issuer in a list. + * + * @param issuerType the issuer type + * @param index the start position index + * @param num the number of issuers + * @return the list + */ + @Override + public ResponseData> getAllSpecificTypeIssuerList( + String issuerType, + Integer index, + Integer num + ) { + SpecificTypeValue specificTypeValue = getDataDriver().getSpecificType(DataDriverConstant.LOCAL_SPECIFIC_ISSUER, issuerType).getResult(); + if(specificTypeValue == null || specificTypeValue.getFellow().equals(StringUtils.EMPTY)){ + logger.error("[getAllSpecificTypeIssuerList] issuerType not exist on chain"); + return new ResponseData<>(null, ErrorCode.SPECIFIC_ISSUER_CONTRACT_ERROR_ALREADY_NOT_EXIST); + } + String[] fellows = specificTypeValue.getFellow().split(","); + List fellowList = Arrays.asList(fellows); + if (fellows.length<=index) { + logger.error("[getAllSpecificTypeIssuerList] input argument is illegal"); + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + if(fellows.length>index + num - 1){ + return new ResponseData<>(fellowList.subList(index, index + num), ErrorCode.SUCCESS); + } else { + return new ResponseData<>(fellowList.subList(index, fellows.length - 1), ErrorCode.SUCCESS); + } + } + + @Override + public ResponseData getWeIdFromOrgId(String orgId) { + if (StringUtils.isEmpty(orgId)) { + logger.error("[getWeIdFromOrgId] input argument is illegal"); + return new ResponseData<>(StringUtils.EMPTY, ErrorCode.ILLEGAL_INPUT); + } + AuthorityIssuerInfo authorityIssuerInfo = getDataDriver().getAuthorityIssuerByName(DataDriverConstant.LOCAL_AUTHORITY_ISSUER, orgId).getResult(); + if (WeIdConstant.EMPTY_ADDRESS.equalsIgnoreCase(WeIdUtils.convertWeIdToAddress(authorityIssuerInfo.getWeid()))) { + return new ResponseData<>(StringUtils.EMPTY, + ErrorCode.AUTHORITY_ISSUER_CONTRACT_ERROR_NOT_EXISTS); + } + return new ResponseData<>(authorityIssuerInfo.getWeid(), ErrorCode.SUCCESS); + } + + @Override + public ResponseData getIssuerCount() { + try { + return getDataDriver().getAuthorityIssuerCount(DataDriverConstant.LOCAL_AUTHORITY_ISSUER); + } catch (Exception e) { + logger.error("[getIssuerCount] getIssuerCount has error, Error Message:{}", e); + return new ResponseData<>(0, ErrorCode.PERSISTENCE_EXECUTE_FAILED); + } + } + + @Override + public ResponseData getRecognizedIssuerCount() { + try { + return getDataDriver().getRecognizedIssuerCount(DataDriverConstant.LOCAL_AUTHORITY_ISSUER); + } catch (Exception e) { + logger.error("[getRecognizedIssuerCount] getRecognizedIssuerCount has error, Error Message:{}", e); + return new ResponseData<>(0, ErrorCode.PERSISTENCE_EXECUTE_FAILED); + } + } + + @Override + public ResponseData getSpecificTypeIssuerSize(String issuerType) { + if (StringUtils.isEmpty(issuerType)) { + logger.error("[getSpecificTypeIssuerSize] input argument is illegal"); + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + SpecificTypeValue specificTypeValue = getDataDriver().getSpecificType(DataDriverConstant.LOCAL_SPECIFIC_ISSUER, issuerType).getResult(); + if(specificTypeValue == null){ + logger.error("[getSpecificTypeIssuerSize] issuerType not exist on chain"); + return new ResponseData<>(null, ErrorCode.SPECIFIC_ISSUER_CONTRACT_ERROR_ALREADY_NOT_EXIST); + } + if(specificTypeValue.getFellow() == null){ + logger.error("[getSpecificTypeIssuerSize] issuerType has not fellow"); + return new ResponseData<>(0, ErrorCode.SUCCESS); + } + String[] fellows = specificTypeValue.getFellow().split(","); + return new ResponseData<>(fellows.length, ErrorCode.SUCCESS); + } + + @Override + public ResponseData getIssuerTypeCount() { + try { + return getDataDriver().getIssuerTypeCount(DataDriverConstant.LOCAL_SPECIFIC_ISSUER); + } catch (Exception e) { + logger.error("[getIssuerTypeCount] getIssuerTypeCount has error, Error Message:{}", e); + return new ResponseData<>(0, ErrorCode.PERSISTENCE_EXECUTE_FAILED); + } + } + + @Override + public ResponseData removeIssuerType( + String privateKey, + String issuerType + ) { + if (StringUtils.isEmpty(issuerType) ||StringUtils.isEmpty(privateKey)) { + logger.error("[removeIssuerType] input argument is illegal"); + return new ResponseData<>(false, ErrorCode.ILLEGAL_INPUT); + } + SpecificTypeValue specificTypeValue = getDataDriver().getSpecificType(DataDriverConstant.LOCAL_SPECIFIC_ISSUER, issuerType).getResult(); + if(specificTypeValue.getFellow() != null){ + logger.error("[removeIssuerType] has issuer in the specific issuer type"); + return new ResponseData<>(false, ErrorCode.SPECIFIC_ISSUER_CONTRACT_ERROR_EXIST_ISSUER); + } + if(!specificTypeValue.getOwner().equals(WeIdUtils.getWeIdFromPrivateKey(privateKey))){ + logger.error("[removeIssuerType] no permission to removeIssuerType"); + return new ResponseData<>(false, ErrorCode.CONTRACT_ERROR_NO_PERMISSION); + } + ResponseData resp = + getDataDriver().removeSpecificType( + DataDriverConstant.LOCAL_SPECIFIC_ISSUER, + issuerType); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[removeIssuerType] delete IssuerType from db failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(true, ErrorCode.SUCCESS); + } + + @Override + public ResponseData> getIssuerTypeList(Integer index, Integer num) { + try { + List typeNameList= getDataDriver().getIssuerTypeList( + DataDriverConstant.LOCAL_SPECIFIC_ISSUER, + index, + index + num).getResult(); + List issuerTypeList = new ArrayList<>(); + for (String typeName : typeNameList) { + SpecificTypeValue specificTypeValue = getDataDriver().getSpecificType(DataDriverConstant.LOCAL_SPECIFIC_ISSUER, typeName).getResult(); + IssuerType issuerType = new IssuerType(); + issuerType.setTypeName(typeName); + issuerType.setCreated(specificTypeValue.getCreated().getTime()); + issuerType.setOwner(specificTypeValue.getOwner()); + issuerTypeList.add(issuerType); + } + return new ResponseData<>(issuerTypeList, ErrorCode.SUCCESS); + } catch (Exception e) { + logger.error("[getIssuerTypeList] getIssuerTypeList has error, Error Message:{}", e); + return new ResponseData<>(null, ErrorCode.PERSISTENCE_EXECUTE_FAILED); + } + } + +} diff --git a/src/main/java/com/webank/weid/service/local/CptServiceLocal.java b/src/main/java/com/webank/weid/service/local/CptServiceLocal.java new file mode 100644 index 000000000..7e07ebfd2 --- /dev/null +++ b/src/main/java/com/webank/weid/service/local/CptServiceLocal.java @@ -0,0 +1,335 @@ +package com.webank.weid.service.local; + +import com.webank.wedpr.selectivedisclosure.CredentialTemplateEntity; +import com.webank.wedpr.selectivedisclosure.proto.AttributeTemplate; +import com.webank.wedpr.selectivedisclosure.proto.TemplatePublicKey; +import com.webank.weid.blockchain.constant.ChainType; +import com.webank.weid.blockchain.constant.ErrorCode; +import com.webank.weid.blockchain.constant.WeIdConstant; +import com.webank.weid.blockchain.protocol.base.Cpt; +import com.webank.weid.blockchain.protocol.base.CptBaseInfo; +import com.webank.weid.blockchain.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.RsvSignature; +import com.webank.weid.blockchain.rpc.CptService; +import com.webank.weid.blockchain.service.impl.CptServiceImpl; +import com.webank.weid.util.JsonUtil; +import com.webank.weid.constant.DataDriverConstant; +import com.webank.weid.exception.DatabaseException; +import com.webank.weid.protocol.base.GlobalStatus; +import com.webank.weid.service.local.role.RoleController; +import com.webank.weid.suite.persistence.CptValue; +import com.webank.weid.suite.persistence.Persistence; +import com.webank.weid.suite.persistence.PersistenceFactory; +import com.webank.weid.suite.persistence.PersistenceType; +import com.webank.weid.util.DataToolUtils; +import com.webank.weid.util.PropertyUtils; +import com.webank.weid.util.WeIdUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Component("cptServiceLocal") +public class CptServiceLocal implements CptService { + /** + * log4j object, for recording log. + */ + private static final Logger logger = LoggerFactory.getLogger(CptServiceLocal.class); + + private static Persistence dataDriver; + private static PersistenceType persistenceType; + public static Integer AUTHORITY_ISSUER_START_ID = 1000; + public static Integer NONE_AUTHORITY_ISSUER_START_ID = 2000000; + WeIdServiceLocal weIdServiceLocal = new WeIdServiceLocal(); + AuthorityIssuerServiceLocal authorityIssuerServiceLocal = new AuthorityIssuerServiceLocal(); + + private static 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; + } + + /** + * Register a new CPT with a pre-set CPT ID, to the blockchain. + * + * @param address the address of creator + * @param cptJsonSchemaNew the new cptJsonSchema + * @param rsvSignature the rsvSignature of cptJsonSchema + * @param privateKey the decimal privateKey of creator + * @param cptId the CPT ID + * @return response data + */ + public ResponseData registerCpt( + String address, + String cptJsonSchemaNew, + RsvSignature rsvSignature, + String privateKey, + Integer cptId) { + if (StringUtils.isEmpty(address) || StringUtils.isEmpty(cptJsonSchemaNew) || StringUtils.isEmpty(privateKey)) { + logger.error("[registerCpt] input argument is illegal"); + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + //如果不存在该weId则报错 + if(!weIdServiceLocal.isWeIdExist(WeIdUtils.convertAddressToWeId(address)).getResult()){ + logger.error("[registerCpt] the weid of publisher does not exist on blockchain"); + return new ResponseData<>(null, ErrorCode.CPT_PUBLISHER_NOT_EXIST); + } + if(getDataDriver().getCpt(DataDriverConstant.LOCAL_CPT, cptId).getResult() != null){ + logger.error("[registerCpt] cpt already exist on chain"); + return new ResponseData<>(null, ErrorCode.CPT_ALREADY_EXIST); + } + if(cptId < AUTHORITY_ISSUER_START_ID){ + if(!RoleController.checkPermission(WeIdUtils.getWeIdFromPrivateKey(privateKey), RoleController.MODIFY_AUTHORITY_ISSUER)){ + logger.error("[registerCpt] operator has not committee member permission to registerCpt"); + return new ResponseData<>(null, ErrorCode.CPT_NO_PERMISSION); + } + }else if(cptId < NONE_AUTHORITY_ISSUER_START_ID){ + if(!RoleController.checkPermission(WeIdUtils.getWeIdFromPrivateKey(privateKey), RoleController.MODIFY_KEY_CPT)){ + logger.error("[registerCpt] operator has not authority issuer permission to registerCpt"); + return new ResponseData<>(null, ErrorCode.CPT_NO_PERMISSION); + } + } + ResponseData resp = + getDataDriver().addCpt( + DataDriverConstant.LOCAL_CPT, + cptId, + address, + null, + cptJsonSchemaNew, + com.webank.weid.blockchain.util.DataToolUtils.SigBase64Serialization(rsvSignature)); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[registerCpt] save cpt to db failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(resp.getResult(), ErrorCode.SUCCESS); + } + + /** + * This is used to register a new CPT to the blockchain. + * + * @param address the address of creator + * @param cptJsonSchemaNew the new cptJsonSchema + * @param rsvSignature the rsvSignature of cptJsonSchema + * @param privateKey the decimal privateKey of creator + * @return the response data + */ + public ResponseData registerCpt( + String address, + String cptJsonSchemaNew, + RsvSignature rsvSignature, + String privateKey) { + if (StringUtils.isEmpty(address) || StringUtils.isEmpty(cptJsonSchemaNew) || StringUtils.isEmpty(privateKey)) { + logger.error("[registerCpt] input argument is illegal"); + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + //如果不存在该weId则报错 + if(!weIdServiceLocal.isWeIdExist(WeIdUtils.convertAddressToWeId(address)).getResult()){ + logger.error("[registerCpt] the weid of publisher does not exist on blockchain"); + return new ResponseData<>(null, ErrorCode.CPT_PUBLISHER_NOT_EXIST); + } + int cptId = getCptId(address); + + ResponseData resp = + getDataDriver().addCpt( + DataDriverConstant.LOCAL_CPT, + cptId, + address, + null, + cptJsonSchemaNew, + com.webank.weid.blockchain.util.DataToolUtils.SigBase64Serialization(rsvSignature)); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[registerCpt] save cpt to db failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(resp.getResult(), ErrorCode.SUCCESS); + } + + public int getCptId(String address) { + GlobalStatus globalStatus = GlobalStatus.readStatusFromFile("global.status"); + if(authorityIssuerServiceLocal.isAuthorityIssuer(address).getResult()){ + int cptId = globalStatus.getAuthority_issuer_current_cpt_id(); + while (getDataDriver().getCpt(DataDriverConstant.LOCAL_CPT, cptId).getResult() != null) { + cptId++; + } + globalStatus.setAuthority_issuer_current_cpt_id(cptId); + GlobalStatus.storeStatusToFile(globalStatus, "global.status"); + if(cptId > NONE_AUTHORITY_ISSUER_START_ID) cptId = 0; + return cptId; + } else { + int cptId = globalStatus.getNone_authority_issuer_current_cpt_id(); + while (getDataDriver().getCpt(DataDriverConstant.LOCAL_CPT, cptId).getResult() != null) { + cptId++; + } + globalStatus.setNone_authority_issuer_current_cpt_id(cptId); + GlobalStatus.storeStatusToFile(globalStatus, "global.status"); + return cptId; + } + } + + /** + * this is used to query cpt with the latest version which has been registered. + * + * @param cptId the cpt id + * @return the response data + */ + public ResponseData queryCpt(Integer cptId) { + try { + CptValue cptValue = getDataDriver().getCpt(DataDriverConstant.LOCAL_CPT, cptId).getResult(); + if(cptValue == null){ + logger.error("[queryCpt] cpt not exist on chain"); + return new ResponseData<>(null, ErrorCode.CPT_NOT_EXISTS); + } + Cpt cpt = new Cpt(); + cpt.setCptId(cptId); + cpt.setCptVersion(cptValue.getCpt_version()); + cpt.setCptPublisher(cptValue.getPublisher()); + cpt.setCptSignature(cptValue.getCpt_signature()); + Map jsonSchemaMap = DataToolUtils + .deserialize(cptValue.getCpt_schema(), HashMap.class); + cpt.setCptJsonSchema(jsonSchemaMap); + return new ResponseData<>(cpt, ErrorCode.SUCCESS); + } catch (Exception e) { + logger.error("[queryCpt] execute failed. Error message :{}", e); + return new ResponseData<>(null, ErrorCode.PERSISTENCE_EXECUTE_FAILED); + } + } + + /** + * This is used to update a CPT data which has been register. + * + * @param address the address of creator + * @param cptJsonSchemaNew the new cptJsonSchema + * @param rsvSignature the rsvSignature of cptJsonSchema + * @param privateKey the decimal privateKey of creator + * @param cptId the CPT ID + * @return the response data + */ + public ResponseData updateCpt(String address, + String cptJsonSchemaNew, + RsvSignature rsvSignature, + String privateKey, + Integer cptId) { + if (StringUtils.isEmpty(address) || StringUtils.isEmpty(cptJsonSchemaNew) || StringUtils.isEmpty(privateKey)) { + logger.error("[updateCpt] input argument is illegal"); + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + if(!weIdServiceLocal.isWeIdExist(com.webank.weid.util.WeIdUtils.convertAddressToWeId(address)).getResult()){ + logger.error("[updateCpt] the weid of publisher does not exist on blockchain"); + return new ResponseData<>(null, ErrorCode.CPT_PUBLISHER_NOT_EXIST); + } + CptValue cptValue = getDataDriver().getCpt(DataDriverConstant.LOCAL_CPT, cptId).getResult(); + if(cptValue == null){ + logger.error("[updateCpt] cpt not exist on chain"); + return new ResponseData<>(null, ErrorCode.CPT_NOT_EXISTS); + } + if(!cptValue.getPublisher().equals(address)){ + logger.error("[updateCpt] cpt publisher of this cpt is not equal to the address"); + return new ResponseData<>(null, ErrorCode.CPT_NO_PERMISSION); + } + ResponseData resp = + getDataDriver().updateCpt( + DataDriverConstant.LOCAL_CPT, + cptId, + cptValue.getCpt_version() + 1, + address, + cptValue.getDescription(), + cptJsonSchemaNew, + com.webank.weid.blockchain.util.DataToolUtils.SigBase64Serialization(rsvSignature)); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[updateCpt] update cpt to db failed."); + throw new DatabaseException("database error!"); + } + CptBaseInfo cptBaseInfo = new CptBaseInfo(); + cptBaseInfo.setCptId(cptId); + cptBaseInfo.setCptVersion(cptValue.getCpt_version() + 1); + return new ResponseData<>(cptBaseInfo, ErrorCode.SUCCESS); + } + + @Override + public ResponseData putCredentialTemplate(Integer cptId, String credentialPublicKey, String credentialKeyCorrectnessProof) { + if (StringUtils.isEmpty(credentialPublicKey) || StringUtils.isEmpty(credentialKeyCorrectnessProof)) { + logger.error("[putCredentialTemplate] input argument is illegal"); + return new ResponseData<>(false, ErrorCode.ILLEGAL_INPUT); + } + CptValue cptValue = getDataDriver().getCpt(DataDriverConstant.LOCAL_CPT, cptId).getResult(); + if(cptValue == null){ + logger.error("[putCredentialTemplate] cpt not exist on chain"); + return new ResponseData<>(false, ErrorCode.CPT_NOT_EXISTS); + } + ResponseData resp = + getDataDriver().updateCredentialTemplate( + DataDriverConstant.LOCAL_CPT, + cptId, + credentialPublicKey, + credentialKeyCorrectnessProof); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[putCredentialTemplate] update credential template to db failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(true, ErrorCode.SUCCESS); + } + + @Override + public ResponseData queryCredentialTemplate(Integer cptId) { + try { + CptValue cptValue = getDataDriver().getCpt(DataDriverConstant.LOCAL_CPT, cptId).getResult(); + if(cptValue == null){ + logger.error("[queryCredentialTemplate] cpt not exist on chain"); + return new ResponseData<>(null, ErrorCode.CPT_NOT_EXISTS); + } + CredentialTemplateEntity credentialTemplateEntity = new CredentialTemplateEntity(); + TemplatePublicKey pubKey = TemplatePublicKey.newBuilder().setCredentialPublicKey(cptValue.getCredential_publicKey()).build(); + credentialTemplateEntity.setPublicKey(pubKey); + credentialTemplateEntity.setCredentialKeyCorrectnessProof(cptValue.getCredential_proof()); + Map cptInfo = DataToolUtils + .deserialize(cptValue.getCpt_schema(), HashMap.class); + List attrList; + attrList = JsonUtil.extractCptProperties(cptInfo); + AttributeTemplate.Builder builder = AttributeTemplate.newBuilder(); + for (String attr : attrList) { + builder.addAttributeKey(attr); + } + AttributeTemplate attributes = builder.build(); + credentialTemplateEntity.setCredentialSchema(attributes); + return new ResponseData<>(credentialTemplateEntity, ErrorCode.SUCCESS); + } catch (Exception e) { + logger.error("[queryCredentialTemplate] execute failed. Error message :{}", e); + return new ResponseData<>(null, ErrorCode.PERSISTENCE_EXECUTE_FAILED); + } + } + + @Override + public ResponseData> getCptIdList(Integer startPos, Integer num) { + try { + return getDataDriver().getCptIdList( + DataDriverConstant.LOCAL_CPT, + startPos, + startPos + num); + } catch (Exception e) { + logger.error("[getCptIdList] getCptIdList has error, Error Message:{}", e); + return new ResponseData<>(null, ErrorCode.PERSISTENCE_EXECUTE_FAILED); + } + } + + @Override + public ResponseData getCptCount() { + try { + return getDataDriver().getCptCount(DataDriverConstant.LOCAL_CPT); + } catch (Exception e) { + logger.error("[getCptCount] getCptCount has error, Error Message:{}", e); + return new ResponseData<>(0, ErrorCode.PERSISTENCE_EXECUTE_FAILED); + } + } + +} diff --git a/src/main/java/com/webank/weid/service/local/EvidenceServiceLocal.java b/src/main/java/com/webank/weid/service/local/EvidenceServiceLocal.java new file mode 100644 index 000000000..3d3387fc8 --- /dev/null +++ b/src/main/java/com/webank/weid/service/local/EvidenceServiceLocal.java @@ -0,0 +1,441 @@ +package com.webank.weid.service.local; + +import com.webank.weid.blockchain.constant.ChainType; +import com.webank.weid.blockchain.constant.ErrorCode; +import com.webank.weid.blockchain.protocol.base.CptBaseInfo; +import com.webank.weid.blockchain.protocol.base.EvidenceInfo; +import com.webank.weid.blockchain.protocol.base.EvidenceSignInfo; +import com.webank.weid.blockchain.protocol.response.ResponseData; +import com.webank.weid.blockchain.rpc.EvidenceService; +import com.webank.weid.blockchain.util.DataToolUtils; +import com.webank.weid.util.WeIdUtils; +import com.webank.weid.constant.DataDriverConstant; +import com.webank.weid.exception.DatabaseException; +import com.webank.weid.service.local.role.RoleController; +import com.webank.weid.suite.persistence.EvidenceValue; +import com.webank.weid.suite.persistence.Persistence; +import com.webank.weid.suite.persistence.PersistenceFactory; +import com.webank.weid.suite.persistence.PersistenceType; +import com.webank.weid.util.PropertyUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Component("evidenceServiceLocal") +public class EvidenceServiceLocal implements EvidenceService { + private static final Logger logger = LoggerFactory.getLogger(EvidenceServiceLocal.class); + + private static Persistence dataDriver; + private static PersistenceType persistenceType; + public String groupId = "1"; + + private static 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; + } + + @Override + public String getGroupId(){ + return this.groupId; + } + + @Override + public ResponseData createEvidence( + String hashValue, + String signature, + String log, + Long timestamp, + String privateKey + ) { + if (StringUtils.isEmpty(hashValue) || StringUtils.isEmpty(log) || StringUtils.isEmpty(signature) || StringUtils.isEmpty(privateKey)) { + logger.error("[createEvidence] input argument is illegal"); + return new ResponseData<>(StringUtils.EMPTY, ErrorCode.ILLEGAL_INPUT); + } + if(getDataDriver().getEvidenceByHash(DataDriverConstant.LOCAL_EVIDENCE, hashValue).getResult() != null) { + logger.error("[createEvidence] evidence with the hash value already existed"); + return new ResponseData<>(StringUtils.EMPTY, ErrorCode.CREDENTIAL_EVIDENCE_ALREADY_EXISTS); + } + ResponseData resp = + getDataDriver().addEvidenceByHash( + DataDriverConstant.LOCAL_EVIDENCE, + hashValue, + WeIdUtils.getWeIdFromPrivateKey(privateKey), + signature, + log, + String.valueOf(timestamp), + String.valueOf(0), + StringUtils.EMPTY, + groupId); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[createEvidence] save evidence to db failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(hashValue, ErrorCode.SUCCESS); + } + + @Override + public ResponseData createEvidenceWithCustomKey( + String hashValue, + String signature, + String log, + Long timestamp, + String extraKey, + String privateKey + ) { + if (StringUtils.isEmpty(hashValue) || StringUtils.isEmpty(hashValue) || StringUtils.isEmpty(signature) || StringUtils.isEmpty(privateKey)) { + logger.error("[createEvidenceWithCustomKey] input argument is illegal"); + return new ResponseData<>(false, ErrorCode.ILLEGAL_INPUT); + } + if(getDataDriver().getEvidenceByHash(DataDriverConstant.LOCAL_EVIDENCE, hashValue).getResult() != null) { + logger.error("[createEvidenceWithCustomKey] evidence with the hash value already existed"); + return new ResponseData<>(false, ErrorCode.CREDENTIAL_EVIDENCE_ALREADY_EXISTS); + } + + ResponseData resp = + getDataDriver().addEvidenceByHash( + DataDriverConstant.LOCAL_EVIDENCE, + hashValue, + WeIdUtils.getWeIdFromPrivateKey(privateKey), + signature, + log, + String.valueOf(timestamp), + String.valueOf(0), + extraKey, + groupId); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[createEvidenceWithCustomKey] save evidence to db failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(true, ErrorCode.SUCCESS); + } + + /** + * Get the evidence from blockchain. + * + * @param hashValue the evidence hash on chain + * @return The EvidenceInfo + */ + @Override + public ResponseData getInfo(String hashValue) { + if (StringUtils.isEmpty(hashValue)) { + logger.error("[getInfo] input argument is illegal"); + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + EvidenceInfo evidenceInfo = new EvidenceInfo(); + evidenceInfo.setCredentialHash(hashValue); + EvidenceValue evidenceValue = getDataDriver().getEvidenceByHash(DataDriverConstant.LOCAL_EVIDENCE, hashValue).getResult(); + if(evidenceValue == null){ + logger.error("[getInfo] evidence not exist on chain"); + return new ResponseData<>(null, ErrorCode.CREDENTIAL_EVIDENCE_NOT_EXIST); + } + Map signInfoMap = new HashMap<>(); + String[] signerList = evidenceValue.getSigners().split(";"); + String[] signatureList = evidenceValue.getSignatures().split(";"); + String[] timestampList = evidenceValue.getUpdated().split(";"); + String[] logList = evidenceValue.getLogs().split(";"); + String[] revokedList = evidenceValue.getRevoked().split(";"); + for(int i = 0; i < signerList.length; i++){ + if(signInfoMap.containsKey(WeIdUtils.convertWeIdToAddress(signerList[i]))){ + EvidenceSignInfo evidenceSignInfo = signInfoMap.get(WeIdUtils.convertWeIdToAddress(signerList[i])); + if(!signatureList[i].equals("empty signature")) evidenceSignInfo.setSignature(signatureList[i]); + evidenceSignInfo.setTimestamp(timestampList[i]); + evidenceSignInfo.setRevoked(revokedList[i].equals("1")); + List logs = evidenceSignInfo.getLogs(); + logs.add(logList[i]); + evidenceSignInfo.setLogs(logs); + signInfoMap.put(WeIdUtils.convertWeIdToAddress(signerList[i]), evidenceSignInfo); + } else { + EvidenceSignInfo evidenceSignInfo = new EvidenceSignInfo(); + if(!signatureList[i].equals("empty signature")) evidenceSignInfo.setSignature(signatureList[i]); + evidenceSignInfo.setTimestamp(timestampList[i]); + evidenceSignInfo.setRevoked(revokedList[i].equals("1")); + List logs = evidenceSignInfo.getLogs(); + logs.add(logList[i]); + evidenceSignInfo.setLogs(logs); + signInfoMap.put(WeIdUtils.convertWeIdToAddress(signerList[i]), evidenceSignInfo); + } + } + evidenceInfo.setSignInfo(signInfoMap); + return new ResponseData<>(evidenceInfo, ErrorCode.SUCCESS); + } + + @Override + public ResponseData> batchCreateEvidence( + List hashValues, + List signatures, + List logs, + List timestamps, + List signers, + String privateKey + ) { + if (hashValues.size() != signatures.size() || hashValues.size() != logs.size() || hashValues.size() != timestamps.size() || hashValues.size() != signers.size()) { + logger.error("[batchCreateEvidence] input argument is illegal"); + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + List resultList = new ArrayList<>(); + for(int i = 0; i < hashValues.size(); i++){ + if (StringUtils.isEmpty(hashValues.get(i)) || StringUtils.isEmpty(logs.get(i)) || StringUtils.isEmpty(signatures.get(i)) || StringUtils.isEmpty(signers.get(i))) { + logger.error("[batchCreateEvidence] input argument is illegal"); + resultList.add(false); + continue; + } + if(getDataDriver().getEvidenceByHash(DataDriverConstant.LOCAL_EVIDENCE, hashValues.get(i)).getResult() != null) { + logger.error("[batchCreateEvidence] evidence with the hash value already existed"); + resultList.add(false); + continue; + } + ResponseData resp = + getDataDriver().addEvidenceByHash( + DataDriverConstant.LOCAL_EVIDENCE, + hashValues.get(i), + signers.get(i), + signatures.get(i), + logs.get(i), + String.valueOf(timestamps.get(i)), + String.valueOf(0), + StringUtils.EMPTY, + groupId); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[batchCreateEvidence] batch save evidence to db failed."); + resultList.add(false); + continue; + } + resultList.add(true); + } + return new ResponseData<>(resultList, ErrorCode.SUCCESS); + } + + @Override + public ResponseData> batchCreateEvidenceWithCustomKey( + List hashValues, + List signatures, + List logs, + List timestamps, + List signers, + List extraKeys, + String privateKey + ) { + if (hashValues.size() != signatures.size() || hashValues.size() != logs.size() || hashValues.size() != timestamps.size() || hashValues.size() != signers.size() || hashValues.size() != extraKeys.size()) { + logger.error("[batchCreateEvidenceWithCustomKey] input argument is illegal"); + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + List resultList = new ArrayList<>(); + for(int i = 0; i < hashValues.size(); i++){ + if (StringUtils.isEmpty(hashValues.get(i)) || StringUtils.isEmpty(logs.get(i)) || StringUtils.isEmpty(signatures.get(i)) || StringUtils.isEmpty(signers.get(i))) { + logger.error("[batchCreateEvidenceWithCustomKey] input argument is illegal"); + resultList.add(false); + continue; + } + if(getDataDriver().getEvidenceByHash(DataDriverConstant.LOCAL_EVIDENCE, hashValues.get(i)).getResult() != null) { + logger.error("[batchCreateEvidenceWithCustomKey] evidence with the hash value already existed"); + resultList.add(false); + continue; + } + ResponseData resp = + getDataDriver().addEvidenceByHash( + DataDriverConstant.LOCAL_EVIDENCE, + hashValues.get(i), + signers.get(i), + signatures.get(i), + logs.get(i), + String.valueOf(timestamps.get(i)), + String.valueOf(0), + extraKeys.get(i), + groupId); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[batchCreateEvidenceWithCustomKey] batch save evidence to db failed."); + resultList.add(false); + continue; + } + resultList.add(true); + } + return new ResponseData<>(resultList, ErrorCode.SUCCESS); + } + + @Override + public ResponseData addLog( + String hashValue, + String signature, + String log, + Long timestamp, + String privateKey + ) { + if (StringUtils.isEmpty(hashValue) || StringUtils.isEmpty(log) || StringUtils.isEmpty(privateKey)) { + logger.error("[addLog] input argument is illegal"); + return new ResponseData<>(false, ErrorCode.ILLEGAL_INPUT); + } + EvidenceValue evidenceValue = getDataDriver().getEvidenceByHash(DataDriverConstant.LOCAL_EVIDENCE, hashValue).getResult(); + if(evidenceValue == null) { + logger.error("[addLog] evidence with the hash value not existed"); + return new ResponseData<>(false, ErrorCode.CREDENTIAL_EVIDENCE_NOT_EXIST); + } + if(signature.equals(StringUtils.EMPTY)) signature = "empty signature"; + ResponseData resp = + getDataDriver().addSignatureAndLogs( + DataDriverConstant.LOCAL_EVIDENCE, + hashValue, + evidenceValue.getSigners() + ';' + WeIdUtils.getWeIdFromPrivateKey(privateKey), + evidenceValue.getSignatures() + ';' + signature, + evidenceValue.getLogs() + ';' + log, + evidenceValue.getUpdated() + ';' + timestamp, + evidenceValue.getRevoked() + ';' + 0, + evidenceValue.getExtra_key()); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[addLog] update evidence to db failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(true, ErrorCode.SUCCESS); + } + + /** + * Get the hash info from blockchain using custom key. + * + * @param customKey the customKey on chain + * @return The EvidenceInfo + */ + @Override + public ResponseData getHashByCustomKey(String customKey) { + if (StringUtils.isEmpty(customKey)) { + logger.error("[getHashByCustomKey] input argument is illegal"); + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + EvidenceValue evidenceValue = getDataDriver().getEvidenceByExtraKey(DataDriverConstant.LOCAL_EVIDENCE, customKey).getResult(); + if(evidenceValue == null){ + logger.error("[getHashByCustomKey] evidence not exist on chain"); + return new ResponseData<>(null, ErrorCode.CREDENTIAL_EVIDENCE_NOT_EXIST); + } + + return new ResponseData<>(evidenceValue.getHash(), ErrorCode.SUCCESS); + } + + @Override + public ResponseData addLogByCustomKey( + String hashValue, + String signature, + String log, + Long timestamp, + String customKey, + String privateKey + ) { + if (StringUtils.isEmpty(hashValue) || StringUtils.isEmpty(log) || StringUtils.isEmpty(privateKey) || StringUtils.isEmpty(customKey)) { + logger.error("[addLogByCustomKey] input argument is illegal"); + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + EvidenceValue evidenceValue = getDataDriver().getEvidenceByHash(DataDriverConstant.LOCAL_EVIDENCE, hashValue).getResult(); + if(evidenceValue == null){ + logger.error("[addLogByCustomKey] evidence not exist on chain"); + return new ResponseData<>(null, ErrorCode.CREDENTIAL_EVIDENCE_NOT_EXIST); + } + if(signature.equals(StringUtils.EMPTY)) signature = "empty signature"; + ResponseData resp = + getDataDriver().addSignatureAndLogs( + DataDriverConstant.LOCAL_EVIDENCE, + hashValue, + evidenceValue.getSigners() + ';' + WeIdUtils.getWeIdFromPrivateKey(privateKey), + evidenceValue.getSignatures() + ';' + signature, + evidenceValue.getLogs() + ';' + log, + evidenceValue.getUpdated() + ';' + timestamp, + evidenceValue.getRevoked() + ';' + 0, + customKey); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[addLogByCustomKey] update evidence to db failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(true, ErrorCode.SUCCESS); + } + + /** + * Get the evidence from blockchain. + * + * @param customKey the evidence hash on chain + * @return The EvidenceInfo + */ + @Override + public ResponseData getInfoByCustomKey(String customKey) { + if (StringUtils.isEmpty(customKey)) { + logger.error("[getInfo] input argument is illegal"); + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + EvidenceValue evidenceValue = getDataDriver().getEvidenceByExtraKey(DataDriverConstant.LOCAL_EVIDENCE, customKey).getResult(); + if(evidenceValue == null){ + logger.error("[getInfo] evidence not exist on chain"); + return new ResponseData<>(null, ErrorCode.CREDENTIAL_EVIDENCE_NOT_EXIST); + } + return getInfo(evidenceValue.getHash()); + } + + /** + * Revoke an evidence - which can be un-revoked. + * + * @param hash the hash + * @param revokeStage the revokeStage + * @param timestamp the timestamp + * @param privateKey the weid privateKey + * @return true if yes, false otherwise, with error codes + */ + @Override + public ResponseData revoke(String hash, Boolean revokeStage, Long timestamp, String privateKey) { + if (StringUtils.isEmpty(hash) || StringUtils.isEmpty(privateKey)) { + logger.error("[revoke] input argument is illegal"); + return new ResponseData<>(false, ErrorCode.ILLEGAL_INPUT); + } + EvidenceValue evidenceValue = getDataDriver().getEvidenceByHash(DataDriverConstant.LOCAL_EVIDENCE, hash).getResult(); + if(evidenceValue == null) { + logger.error("[revoke] evidence with the hash value not existed"); + return new ResponseData<>(false, ErrorCode.CREDENTIAL_EVIDENCE_NOT_EXIST); + } + String[] signerList = evidenceValue.getSigners().split(";"); + String[] revokedList = evidenceValue.getRevoked().split(";"); + String[] timestampList = evidenceValue.getUpdated().split(";"); + String revoked = revokedList[0]; + String timestampStr = timestampList[0]; + for(int i = 0; i < signerList.length; i++){ + if(signerList[i].equals(WeIdUtils.getWeIdFromPrivateKey(privateKey))){ + revokedList[i] = String.valueOf(revokeStage? 1:0); + timestampList[i] = String.valueOf(timestamp); + } + } + String newRevoked = revokedList[0]; + if(revokedList.length != 1) { + for(int i = 1; i < revokedList.length; i++){ + newRevoked = newRevoked + ';' + revokedList[i]; + } + } + String newTimestamp = timestampList[0]; + if(timestampList.length != 1) { + for(int i = 1; i < timestampList.length; i++){ + newTimestamp = newTimestamp + ';' + timestampList[i]; + } + } + ResponseData resp = + getDataDriver().addSignatureAndLogs( + DataDriverConstant.LOCAL_EVIDENCE, + hash, + evidenceValue.getSigners(), + evidenceValue.getSignatures(), + evidenceValue.getLogs(), + newTimestamp, + newRevoked, + evidenceValue.getExtra_key()); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[revoke] update evidence to db failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(true, ErrorCode.SUCCESS); + } + +} diff --git a/src/main/java/com/webank/weid/service/local/PolicyServiceLocal.java b/src/main/java/com/webank/weid/service/local/PolicyServiceLocal.java new file mode 100644 index 000000000..8dfc6a539 --- /dev/null +++ b/src/main/java/com/webank/weid/service/local/PolicyServiceLocal.java @@ -0,0 +1,308 @@ +package com.webank.weid.service.local; + +import com.webank.weid.blockchain.constant.ChainType; +import com.webank.weid.blockchain.constant.ErrorCode; +import com.webank.weid.blockchain.constant.WeIdConstant; +import com.webank.weid.blockchain.protocol.base.Cpt; +import com.webank.weid.blockchain.protocol.base.CptBaseInfo; +import com.webank.weid.blockchain.protocol.base.PresentationPolicyE; +import com.webank.weid.blockchain.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.RsvSignature; +import com.webank.weid.blockchain.rpc.PolicyService; +import com.webank.weid.util.DataToolUtils; +import com.webank.weid.constant.DataDriverConstant; +import com.webank.weid.exception.DatabaseException; +import com.webank.weid.protocol.base.GlobalStatus; +import com.webank.weid.suite.persistence.*; +import com.webank.weid.util.PropertyUtils; +import com.webank.weid.util.WeIdUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Component("policyServiceLocal") +public class PolicyServiceLocal implements PolicyService { + /** + * log4j object, for recording log. + */ + private static final Logger logger = LoggerFactory.getLogger(PolicyServiceLocal.class); + + private static Persistence dataDriver; + private static PersistenceType persistenceType; + WeIdServiceLocal weIdServiceLocal = new WeIdServiceLocal(); + AuthorityIssuerServiceLocal authorityIssuerServiceLocal = new AuthorityIssuerServiceLocal(); + CptServiceLocal cptServiceLocal = new CptServiceLocal(); + + private static 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; + } + + /** + * Put Claim Policy List on blockchain under a CPT ID. + * + * @param cptId CPT ID + * @param policies Policy list + * @param privateKey privateKey of cpt issuer + * @return claimPolicyId the Claim policy ID on-chain + */ + @Override + public ResponseData putPolicyIntoCpt(Integer cptId, List policies, + String privateKey) { + if(getDataDriver().getCpt(DataDriverConstant.LOCAL_CPT, cptId).getResult() == null){ + logger.error("[putPolicyIntoCpt] cpt not exist on chain"); + return new ResponseData<>(null, ErrorCode.CPT_NOT_EXISTS); + } + String policyString = policies.get(0).toString(); + if(policies.size()>1){ + for(int i = 1; i < policies.size(); i++){ + policyString = policyString + "," + policies.get(i).toString(); + } + } + ResponseData resp = + getDataDriver().updateCptClaimPolicies( + DataDriverConstant.LOCAL_CPT, + cptId, + policyString); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[putPolicyIntoCpt] updateCptClaimPolicies to db failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(resp.getResult(), ErrorCode.SUCCESS); + } + + /** + * Register Claim Policy on blockchain. + * + * @param address address of issuer + * @param cptJsonSchemaNew cptJsonSchema + * @param rsvSignature signature of issuer + * @param privateKey privateKey of issuer + * @return claimPolicyId the Claim policy ID on-chain + */ + @Override + public ResponseData registerPolicyData( + String address, + String cptJsonSchemaNew, + RsvSignature rsvSignature, + String privateKey) { + if (StringUtils.isEmpty(address) || StringUtils.isEmpty(cptJsonSchemaNew) || StringUtils.isEmpty(privateKey)) { + logger.error("[registerPolicyData] input argument is illegal"); + return new ResponseData<>(null, ErrorCode.ILLEGAL_INPUT); + } + //如果不存在该weId则报错 + if(!weIdServiceLocal.isWeIdExist(WeIdUtils.convertAddressToWeId(address)).getResult()){ + logger.error("[registerPolicyData] the weid of publisher does not exist on blockchain"); + return new ResponseData<>(null, ErrorCode.WEID_DOES_NOT_EXIST); + } + int policyId = getPolicyId(address); + + ResponseData resp = + getDataDriver().addPolicy( + DataDriverConstant.LOCAL_POLICY, + policyId, + address, + null, + cptJsonSchemaNew, + com.webank.weid.blockchain.util.DataToolUtils.SigBase64Serialization(rsvSignature)); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[registerPolicyData] save policy to db failed."); + throw new DatabaseException("database error!"); + } + if (resp.getResult() != null && resp.getResult() > 0) { + return new ResponseData<>(policyId, ErrorCode.SUCCESS); + } else { + return new ResponseData<>(-1, ErrorCode.UNKNOW_ERROR); + } + } + + public int getPolicyId(String address) { + GlobalStatus globalStatus = GlobalStatus.readStatusFromFile("global.status"); + if(authorityIssuerServiceLocal.isAuthorityIssuer(address).getResult()){ + int policyId = globalStatus.getAuthority_issuer_current_policy_id(); + while (getDataDriver().getPolicy(DataDriverConstant.LOCAL_POLICY, policyId).getResult() != null) { + policyId++; + } + globalStatus.setAuthority_issuer_current_policy_id(policyId); + GlobalStatus.storeStatusToFile(globalStatus, "global.status"); + if(policyId > CptServiceLocal.NONE_AUTHORITY_ISSUER_START_ID) policyId = 0; + return policyId; + } else { + int policyId = globalStatus.getNone_authority_issuer_current_policy_id(); + while (getDataDriver().getPolicy(DataDriverConstant.LOCAL_POLICY, policyId).getResult() != null) { + policyId++; + } + globalStatus.setNone_authority_issuer_current_policy_id(policyId); + GlobalStatus.storeStatusToFile(globalStatus, "global.status"); + return policyId; + } + } + + /** + * Get Claim Policy Json from blockchain given a policy ID. + * + * @param policyId the Claim Policy ID on-chain + * @return the claim Json + */ + @Override + public ResponseData getClaimPolicy(Integer policyId) { + try { + PolicyValue policyValue = getDataDriver().getPolicy(DataDriverConstant.LOCAL_POLICY, policyId).getResult(); + if(policyValue == null){ + logger.error("[getClaimPolicy] policy not exist on chain"); + return new ResponseData<>(StringUtils.EMPTY, ErrorCode.CPT_NOT_EXISTS); + } + return new ResponseData<>(policyValue.getPolicy_schema(), ErrorCode.SUCCESS); + } catch (Exception e) { + logger.error("[getClaimPolicy] execute failed. Error message :{}", e); + return new ResponseData<>(StringUtils.EMPTY, ErrorCode.PERSISTENCE_EXECUTE_FAILED); + } + } + + /** + * Get all claim policies from this CPT ID. + * + * @param cptId cpt id + * @return claim policies list + */ + @Override + public ResponseData> getClaimPoliciesFromCpt(Integer cptId) { + CptValue cptValue = getDataDriver().getCpt(DataDriverConstant.LOCAL_CPT, cptId).getResult(); + if(cptValue == null){ + logger.error("[getClaimPoliciesFromCpt] cpt not exist on chain"); + return new ResponseData<>(null, ErrorCode.CPT_NOT_EXISTS); + } + if(cptValue.getClaim_policies() == null){ + return new ResponseData<>(null, ErrorCode.SUCCESS); + } + String[] policies = cptValue.getClaim_policies().split(","); + List result = new ArrayList<>(); + for (String obj : policies) { + result.add(Integer.valueOf(obj)); + } + return new ResponseData<>(result, ErrorCode.SUCCESS); + } + + /** + * Register Presentation Policy which contains a number of claim policies. + * + * @param claimPolicyIdList claim policies list + * @param privateKey privateKey of weid + * @return the presentation policy id + */ + @Override + public ResponseData registerPresentationPolicy(List claimPolicyIdList, + String privateKey) { + int presentationId = getPresentationId(); + String policyString = claimPolicyIdList.get(0).toString(); + if(claimPolicyIdList.size()>1){ + for(int i = 1; i < claimPolicyIdList.size(); i++){ + policyString = policyString + "," + claimPolicyIdList.get(i).toString(); + } + } + ResponseData resp = + getDataDriver().addPresentation( + DataDriverConstant.LOCAL_PRESENTATION, + presentationId, + WeIdUtils.convertPublicKeyToWeId(privateKey), + policyString); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[registerPresentationPolicy] save presentation to db failed."); + throw new DatabaseException("database error!"); + } + if (resp.getResult() != null && resp.getResult() > 0) { + return new ResponseData<>(resp.getResult(), ErrorCode.SUCCESS); + } else { + return new ResponseData<>(null, ErrorCode.UNKNOW_ERROR); + } + } + + public int getPresentationId() { + GlobalStatus globalStatus = GlobalStatus.readStatusFromFile("global.status"); + int presentationId = globalStatus.getPresentationId(); + while (getDataDriver().getPresentation(DataDriverConstant.LOCAL_PRESENTATION, presentationId).getResult() != null) { + presentationId++; + } + globalStatus.setPresentationId(presentationId); + GlobalStatus.storeStatusToFile(globalStatus, "global.status"); + return presentationId; + } + + /** + * Get Presentation policies under this id from chain. + * + * @param presentationPolicyId presentation policy id + * @return the full presentation policy + */ + @Override + public ResponseData getPresentationPolicy(Integer presentationPolicyId) { + PresentationValue presentationValue = getDataDriver().getPresentation(DataDriverConstant.LOCAL_PRESENTATION, presentationPolicyId).getResult(); + if(presentationValue == null){ + logger.error("[getPresentationPolicy] presentation not exist on chain"); + return new ResponseData<>(null, ErrorCode.CPT_NOT_EXISTS); + } + if(presentationValue.getClaim_policies().equals(StringUtils.EMPTY)){ + logger.error("[getPresentationPolicy] presentation does not have policies"); + return new ResponseData<>(null, ErrorCode.POLICY_SERVICE_NOT_EXISTS); + } + String[] policies = presentationValue.getClaim_policies().split(","); + List result = new ArrayList<>(); + for (String obj : policies) { + result.add(Integer.valueOf(obj)); + } + PresentationPolicyE presentationPolicy = new PresentationPolicyE(); + presentationPolicy.setId(presentationValue.getPresentation_id()); + Map policyMap = new HashMap<>(); + for (Integer id : result) { + policyMap.put(id, null); + } + presentationPolicy.setPolicy(policyMap); + presentationPolicy.setPolicyPublisherWeId(presentationValue.getCreator()); + return new ResponseData<>(presentationPolicy, ErrorCode.SUCCESS); + } + + /** + * Get all claim policies from chain. + * + * @param startPos start position + * @param num batch number + * @return claim policy list + */ + @Override + public ResponseData> getAllClaimPolicies(Integer startPos, Integer num) { + try { + return getDataDriver().getPolicyIdList( + DataDriverConstant.LOCAL_POLICY, + startPos, + startPos + num); + } catch (Exception e) { + logger.error("[getAllClaimPolicies] getAllClaimPolicies has error, Error Message:{}", e); + return new ResponseData<>(null, ErrorCode.PERSISTENCE_EXECUTE_FAILED); + } + } + + @Override + public ResponseData getPolicyCount() { + try { + return getDataDriver().getPolicyCount(DataDriverConstant.LOCAL_POLICY); + } catch (Exception e) { + logger.error("[getPolicyCount] getPolicyCount has error, Error Message:{}", e); + return new ResponseData<>(0, ErrorCode.PERSISTENCE_EXECUTE_FAILED); + } + } +} diff --git a/src/main/java/com/webank/weid/service/local/WeIdServiceLocal.java b/src/main/java/com/webank/weid/service/local/WeIdServiceLocal.java new file mode 100644 index 000000000..68b474ed3 --- /dev/null +++ b/src/main/java/com/webank/weid/service/local/WeIdServiceLocal.java @@ -0,0 +1,252 @@ +package com.webank.weid.service.local; + +import com.webank.weid.blockchain.constant.ErrorCode; +import com.webank.weid.protocol.base.AuthenticationProperty; +import com.webank.weid.protocol.base.ServiceProperty; +import com.webank.weid.protocol.base.WeIdDocument; +import com.webank.weid.protocol.base.WeIdDocumentMetadata; +import com.webank.weid.blockchain.protocol.response.ResponseData; +import com.webank.weid.blockchain.rpc.WeIdService; +import com.webank.weid.util.WeIdUtils; +import com.webank.weid.constant.DataDriverConstant; +import com.webank.weid.exception.DatabaseException; +import com.webank.weid.suite.persistence.Persistence; +import com.webank.weid.suite.persistence.PersistenceFactory; +import com.webank.weid.suite.persistence.PersistenceType; +import com.webank.weid.util.PropertyUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; + +@Component("weIdServiceLocal") +public class WeIdServiceLocal implements WeIdService { + + /** + * log4j object, for recording log. + */ + private static final Logger logger = LoggerFactory.getLogger(WeIdServiceLocal.class); + private static Persistence dataDriver; + private static PersistenceType persistenceType; + + private static 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; + } + + /** + * Check if WeIdentity DID exists on Chain. + * + * @param weId the WeIdentity DID + * @return true if exists, false otherwise + */ + @Override + public ResponseData isWeIdExist(String weId) { + try { + ResponseData dbResp = this.getWeIdDocumentMetadata(weId); + if(dbResp.getResult() != null){ + return new ResponseData<>(true, ErrorCode.SUCCESS); + } + return new ResponseData<>(false, ErrorCode.SUCCESS); + } catch (Exception e) { + logger.error("[isWeIdExist] execute failed. Error message :{}", e); + return new ResponseData<>(false, ErrorCode.UNKNOW_ERROR); + } + } + + /** + * Check if WeIdentity DID is deactivated on Chain. + * + * @param weId the WeIdentity DID + * @return true if is deactivated, false otherwise + */ + @Override + public ResponseData isDeactivated(String weId) { + try { + ResponseData dbResp = this.getWeIdDocumentMetadata(weId); + return new ResponseData<>(dbResp.getResult().isDeactivated(), ErrorCode.SUCCESS); + } catch (Exception e) { + logger.error("[isDeactivated] execute failed. Error message :{}", e); + return new ResponseData<>(false, ErrorCode.UNKNOW_ERROR); + } + } + + @Override + public ResponseData createWeId( + String address, + List authList, + List serviceList, + String privateKey) { + try { + if(authList.size()==0 || serviceList.size()==0){ + return new ResponseData<>(false, ErrorCode.ILLEGAL_INPUT); + } + String weId = WeIdUtils.convertAddressToWeId(address); + //如果已经存在该weId则报错 + if(this.isWeIdExist(weId).getResult()){ + return new ResponseData<>(false, ErrorCode.WEID_ALREADY_EXIST); + } + //创建weIdDocument插入db + WeIdDocument weIdDocument = new WeIdDocument(); + weIdDocument.setId(weId); + List authenticationList = new ArrayList<>(); + for(String authenticationStr : authList){ + AuthenticationProperty authenticationProperty = AuthenticationProperty.fromString(authenticationStr); + authenticationList.add(authenticationProperty); + } + weIdDocument.setAuthentication(authenticationList); + List serList = new ArrayList<>(); + for(String serviceStr : serviceList){ + ServiceProperty serviceProperty = ServiceProperty.fromString(serviceStr); + serList.add(serviceProperty); + } + weIdDocument.setService(serList); + ResponseData resp = + getDataDriver().addWeId( + DataDriverConstant.LOCAL_WEID_DOCUMENT, + weId, + weIdDocument.toJson()); + if (resp.getErrorCode().intValue() != ErrorCode.SUCCESS.getCode()) { + logger.error("[createWeId] save weIdDocument to db failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(true, ErrorCode.SUCCESS); + } catch (Exception e) { + logger.error("[createWeId] create weid failed with exception. ", e); + return new ResponseData<>(false, ErrorCode.PERSISTENCE_EXECUTE_FAILED); + } + } + + /** + * Get a WeIdentity DID Document. + * + * @param weId the WeIdentity DID + * @return the WeIdentity DID document + */ + @Override + public ResponseData getWeIdDocument(String weId) { + try { + return getDataDriver().getWeIdDocument( + DataDriverConstant.LOCAL_WEID_DOCUMENT, + weId); + } catch (Exception e) { + logger.error("[getWeIdDocument] execute failed. Error message :{}", e); + return new ResponseData<>(null, ErrorCode.PERSISTENCE_EXECUTE_FAILED); + } + } + + /** + * Get a WeIdentity DID Document Metadata. + * + * @param weId the WeIdentity DID + * @return the WeIdentity DID document + */ + @Override + public ResponseData getWeIdDocumentMetadata(String weId) { + try { + return getDataDriver().getMeta( + DataDriverConstant.LOCAL_WEID_DOCUMENT, + weId); + } catch (Exception e) { + logger.error("[getWeIdDocumentMetadata] execute failed. Error message :{}", e); + return new ResponseData<>(null, ErrorCode.PERSISTENCE_EXECUTE_FAILED); + } + } + + /** + * call weid contract to update the weid document. + * + * @param weIdDocument weIdDocument on blockchain + * @param address address of the identity + * @param privateKey privateKey identity's private key + * @return result + */ + @Override + public ResponseData updateWeId( + com.webank.weid.blockchain.protocol.base.WeIdDocument weIdDocument, + String privateKey, + String address) { + try { + String weId = WeIdUtils.getWeIdFromPrivateKey(privateKey); + if(!weId.equals(WeIdUtils.convertAddressToWeId(address))){ + logger.error("[updateWeId] the private key does not match the current weid."); + return new ResponseData<>(false, ErrorCode.WEID_PRIVATEKEY_DOES_NOT_MATCH); + } + ResponseData resp = + getDataDriver().updateWeId( + DataDriverConstant.LOCAL_WEID_DOCUMENT, + weId, + weIdDocument.toJson()); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[updateWeId] updateWeId weIdDocument to db failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(true, ErrorCode.SUCCESS); + } catch (Exception e) { + logger.error("[updateWeId] update weid has error, Error Message:{}", e); + return new ResponseData<>(false, ErrorCode.WEID_DOES_NOT_EXIST); + } + } + + @Override + public ResponseData> getWeIdList( + Integer first, + Integer last + ) { + try { + return getDataDriver().getWeIdList( + DataDriverConstant.LOCAL_WEID_DOCUMENT, + first, + last); + } catch (Exception e) { + logger.error("[getWeIdList] getWeIdList has error, Error Message:{}", e); + return new ResponseData<>(null, ErrorCode.PERSISTENCE_EXECUTE_FAILED); + } + } + + @Override + public ResponseData getWeIdCount() { + try { + return getDataDriver().getWeIdCount(DataDriverConstant.LOCAL_WEID_DOCUMENT); + } catch (Exception e) { + logger.error("[getWeIdCount] getWeIdCount has error, Error Message:{}", e); + return new ResponseData<>(0, ErrorCode.PERSISTENCE_EXECUTE_FAILED); + } + } + + /*@Override + public ResponseData deactivateWeId( + String weAddress, + String privateKey) { + try { + String weId = WeIdUtils.getWeIdFromPrivateKey(privateKey); + if(!weId.equals(weAddress)){ + logger.error("[updateWeId] the private key does not match the current weid."); + return new ResponseData<>(false, ErrorCode.WEID_PRIVATEKEY_DOES_NOT_MATCH); + } + ResponseData resp = + getDataDriver().deactivateData( + DataDriverConstant.DOMAIN_WEID_DOCUMENT, + weAddress, + true); + if (resp.getErrorCode().intValue() != ErrorCode.SUCCESS.getCode()) { + logger.error("[deactivateWeId] deactivateWeId failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(true, ErrorCode.SUCCESS); + } catch (Exception e) { + logger.error("[deactivateWeId] deactivate WeId has error, Error Message:{}", e); + return new ResponseData<>(false, ErrorCode.WEID_DOES_NOT_EXIST); + } + }*/ +} diff --git a/src/main/java/com/webank/weid/service/local/role/RoleController.java b/src/main/java/com/webank/weid/service/local/role/RoleController.java new file mode 100644 index 000000000..ec6912f98 --- /dev/null +++ b/src/main/java/com/webank/weid/service/local/role/RoleController.java @@ -0,0 +1,228 @@ +package com.webank.weid.service.local.role; + +import com.webank.weid.blockchain.constant.ErrorCode; +import com.webank.weid.blockchain.protocol.response.ResponseData; +import com.webank.weid.constant.DataDriverConstant; +import com.webank.weid.exception.DatabaseException; +import com.webank.weid.service.local.AuthorityIssuerServiceLocal; +import com.webank.weid.service.local.CptServiceLocal; +import com.webank.weid.service.local.WeIdServiceLocal; +import com.webank.weid.suite.persistence.Persistence; +import com.webank.weid.suite.persistence.PersistenceFactory; +import com.webank.weid.suite.persistence.PersistenceType; +import com.webank.weid.suite.persistence.RoleValue; +import com.webank.weid.util.PropertyUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class RoleController { + + /** + * log4j object, for recording log. + */ + private static final Logger logger = LoggerFactory.getLogger(RoleController.class); + + /** + * Role related Constants. + */ + public static Integer ROLE_AUTHORITY_ISSUER = 100; + public static Integer ROLE_COMMITTEE = 101; + public static Integer ROLE_ADMIN = 102; + + /** + * Operation related Constants. + */ + public static Integer MODIFY_AUTHORITY_ISSUER = 200; + public static Integer MODIFY_COMMITTEE = 201; + public static Integer MODIFY_ADMIN = 202; + public static Integer MODIFY_KEY_CPT = 203; + + private static Persistence dataDriver; + private static PersistenceType persistenceType; + WeIdServiceLocal weIdServiceLocal = new WeIdServiceLocal(); + + private static 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; + } + + public static Boolean checkPermission(String weId, Integer operation) { + RoleValue result = getDataDriver().getRole(DataDriverConstant.LOCAL_ROLE, weId).getResult(); + if(result == null) { + return false; + } + if(operation == RoleController.MODIFY_AUTHORITY_ISSUER) { + if(result.getAdmin_role() == 1 || result.getCommittee_role() == 1) { + return true; + } + } + if(operation == RoleController.MODIFY_COMMITTEE) { + if(result.getAdmin_role() == 1) { + return true; + } + } + if(operation == RoleController.MODIFY_ADMIN) { + if(result.getAdmin_role() == 1) { + return true; + } + } + if(operation == RoleController.MODIFY_KEY_CPT) { + if(result.getAuthority_role() == 1) { + return true; + } + } + return false; + } + + //operator为操作者,相当于tx.origin, weId为操作对象 + public Boolean addRole(String operator, String weId, Integer role) { + if(role == RoleController.ROLE_AUTHORITY_ISSUER) { + //检查操作者权限 + if(checkPermission(operator, RoleController.MODIFY_AUTHORITY_ISSUER)) { + ResponseData resp = + getDataDriver().addRole( + DataDriverConstant.LOCAL_ROLE, + weId, + 1); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[addRole] save role to db failed."); + throw new DatabaseException("database error!"); + } + return true; + } + } + if(role == RoleController.ROLE_COMMITTEE) { + if(checkPermission(operator, RoleController.MODIFY_COMMITTEE)) { + ResponseData resp = + getDataDriver().addRole( + DataDriverConstant.LOCAL_ROLE, + weId, + 2); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[addRole] save role to db failed."); + throw new DatabaseException("database error!"); + } + return true; + } + } + if(role == RoleController.ROLE_ADMIN) { + if(checkPermission(operator, RoleController.MODIFY_ADMIN)) { + ResponseData resp = + getDataDriver().addRole( + DataDriverConstant.LOCAL_ROLE, + weId, + 3); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[addRole] save role to db failed."); + throw new DatabaseException("database error!"); + } + return true; + } + } + return false; + } + + public Boolean removeRole(String operator, String weId, Integer role) { + RoleValue result = getDataDriver().getRole(DataDriverConstant.LOCAL_ROLE, weId).getResult(); + if(role == RoleController.ROLE_AUTHORITY_ISSUER) { + if(checkPermission(operator, RoleController.MODIFY_AUTHORITY_ISSUER)) { + if(result.getAuthority_role() == 1) { + ResponseData resp = + getDataDriver().updateRole( + DataDriverConstant.LOCAL_ROLE, + weId, + computeRoleValue(result)-1); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[removeRole] remove role from db failed."); + throw new DatabaseException("database error!"); + } + return true; + } + logger.error("[removeRole] this weId has not authority role."); + return false; + } + } + if(role == RoleController.ROLE_COMMITTEE) { + if(checkPermission(operator, RoleController.MODIFY_COMMITTEE)) { + if(result.getCommittee_role() == 1) { + ResponseData resp = + getDataDriver().updateRole( + DataDriverConstant.LOCAL_ROLE, + weId, + computeRoleValue(result)-2); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[removeRole] remove role from db failed."); + throw new DatabaseException("database error!"); + } + return true; + } + logger.error("[removeRole] this weId has not committee role."); + return false; + } + } + if(role == RoleController.ROLE_ADMIN) { + if(checkPermission(operator, RoleController.MODIFY_ADMIN)) { + if(result.getAdmin_role() == 1) { + ResponseData resp = + getDataDriver().updateRole( + DataDriverConstant.LOCAL_ROLE, + weId, + computeRoleValue(result)-4); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[removeRole] remove role from db failed."); + throw new DatabaseException("database error!"); + } + return true; + } + logger.error("[removeRole] this weId has not admin role."); + return false; + } + } + return false; + } + + private static int computeRoleValue(RoleValue roleValue) { + if(roleValue.getAuthority_role() == 1){ + if(roleValue.getCommittee_role() == 1){ + if(roleValue.getAdmin_role() == 1){ + return 7; + } + return 3; + }else if(roleValue.getAdmin_role() == 1){ + return 5; + }else {return 1;} + }else if(roleValue.getCommittee_role() == 1){ + if(roleValue.getAdmin_role() == 1){ + return 6; + } + return 2; + }else {return 4;} + } + + public static Boolean checkRole(String weId, Integer role){ + RoleValue result = getDataDriver().getRole(DataDriverConstant.LOCAL_ROLE, weId).getResult(); + if(result == null) { + return false; + } + if(role == RoleController.ROLE_AUTHORITY_ISSUER){ + return result.getAuthority_role() == 1; + } + if(role == RoleController.ROLE_COMMITTEE){ + return result.getCommittee_role() == 1; + } + if(role == RoleController.ROLE_ADMIN){ + return result.getAdmin_role() == 1; + } + logger.error("[checkRole] input role invalid."); + return false; + } + +} diff --git a/src/main/java/com/webank/weid/service/rpc/AuthorityIssuerService.java b/src/main/java/com/webank/weid/service/rpc/AuthorityIssuerService.java index 3497a95df..32f001273 100644 --- a/src/main/java/com/webank/weid/service/rpc/AuthorityIssuerService.java +++ b/src/main/java/com/webank/weid/service/rpc/AuthorityIssuerService.java @@ -10,7 +10,7 @@ import com.webank.weid.protocol.base.WeIdPrivateKey; 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.blockchain.protocol.response.ResponseData; /** * Service inf for operations on Authority Issuer. diff --git a/src/main/java/com/webank/weid/service/rpc/CptService.java b/src/main/java/com/webank/weid/service/rpc/CptService.java index 2c7bfeee1..5661f5058 100644 --- a/src/main/java/com/webank/weid/service/rpc/CptService.java +++ b/src/main/java/com/webank/weid/service/rpc/CptService.java @@ -10,7 +10,7 @@ import com.webank.weid.protocol.base.CptBaseInfo; import com.webank.weid.protocol.request.CptMapArgs; import com.webank.weid.protocol.request.CptStringArgs; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; /** * Service inf for operation on CPT (Claim protocol Type). diff --git a/src/main/java/com/webank/weid/service/rpc/CredentialPojoService.java b/src/main/java/com/webank/weid/service/rpc/CredentialPojoService.java index 9495905c0..11bb928ec 100644 --- a/src/main/java/com/webank/weid/service/rpc/CredentialPojoService.java +++ b/src/main/java/com/webank/weid/service/rpc/CredentialPojoService.java @@ -12,7 +12,7 @@ import com.webank.weid.protocol.base.WeIdPublicKey; import com.webank.weid.protocol.cpt.Cpt101; import com.webank.weid.protocol.request.CreateCredentialPojoArgs; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import java.util.List; import java.util.Set; diff --git a/src/main/java/com/webank/weid/service/rpc/CredentialService.java b/src/main/java/com/webank/weid/service/rpc/CredentialService.java index f0a0a8af2..82c194632 100644 --- a/src/main/java/com/webank/weid/service/rpc/CredentialService.java +++ b/src/main/java/com/webank/weid/service/rpc/CredentialService.java @@ -9,7 +9,7 @@ import com.webank.weid.protocol.base.WeIdPrivateKey; import com.webank.weid.protocol.base.WeIdPublicKey; import com.webank.weid.protocol.request.CreateCredentialArgs; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; /** * Service inf for operations on Credentials. diff --git a/src/main/java/com/webank/weid/service/rpc/EvidenceService.java b/src/main/java/com/webank/weid/service/rpc/EvidenceService.java index 28d0b83c1..16c04b5be 100644 --- a/src/main/java/com/webank/weid/service/rpc/EvidenceService.java +++ b/src/main/java/com/webank/weid/service/rpc/EvidenceService.java @@ -8,7 +8,7 @@ import com.webank.weid.protocol.base.WeIdAuthentication; import com.webank.weid.protocol.base.WeIdPrivateKey; import com.webank.weid.protocol.inf.Hashable; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; /** * Service inf for operations on Evidence for Credentials. diff --git a/src/main/java/com/webank/weid/service/rpc/PolicyService.java b/src/main/java/com/webank/weid/service/rpc/PolicyService.java index bf1d3b5f1..437133ae1 100644 --- a/src/main/java/com/webank/weid/service/rpc/PolicyService.java +++ b/src/main/java/com/webank/weid/service/rpc/PolicyService.java @@ -7,7 +7,7 @@ import com.webank.weid.protocol.base.ClaimPolicy; import com.webank.weid.protocol.base.PresentationPolicyE; import com.webank.weid.protocol.base.WeIdAuthentication; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; /** * Service inf for operation on Policy on blockchain (Claim protocol Type). diff --git a/src/main/java/com/webank/weid/service/rpc/WeIdService.java b/src/main/java/com/webank/weid/service/rpc/WeIdService.java index b9ea3bdb7..7bd1fdf09 100644 --- a/src/main/java/com/webank/weid/service/rpc/WeIdService.java +++ b/src/main/java/com/webank/weid/service/rpc/WeIdService.java @@ -9,7 +9,7 @@ import com.webank.weid.protocol.request.CreateWeIdArgs; import com.webank.weid.protocol.request.ServiceArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.protocol.response.WeIdListResult; diff --git a/src/main/java/com/webank/weid/suite/persistence/AuthorityIssuerInfo.java b/src/main/java/com/webank/weid/suite/persistence/AuthorityIssuerInfo.java new file mode 100644 index 000000000..52f5c5c02 --- /dev/null +++ b/src/main/java/com/webank/weid/suite/persistence/AuthorityIssuerInfo.java @@ -0,0 +1,53 @@ +package com.webank.weid.suite.persistence; + +import lombok.Data; + +import java.util.Date; + +@Data +public class AuthorityIssuerInfo { + /** + * 主键,weid. + */ + private String weid; + + /** + * m名字 + */ + private String name; + + /** + * 描述. + */ + private String description; + + /** + * 创建时间. + */ + private Date created; + + /** + * 更新时间. + */ + private Date updated; + + /** + * 是否已经被确认. + */ + private int recognize; + + /** + * acc_value. + */ + private String acc_value; + + /** + * 附属描述. + */ + private String extra_str; + + /** + * 附属描述. + */ + private String extra_int; +} diff --git a/src/main/java/com/webank/weid/suite/persistence/CptValue.java b/src/main/java/com/webank/weid/suite/persistence/CptValue.java new file mode 100644 index 000000000..5f5fc14e3 --- /dev/null +++ b/src/main/java/com/webank/weid/suite/persistence/CptValue.java @@ -0,0 +1,63 @@ +package com.webank.weid.suite.persistence; + +import lombok.Data; + +import java.util.Date; + +@Data +public class CptValue { + /** + * 主键,cptId. + */ + private int cpt_id; + + /** + * 创建时间. + */ + private Date created; + + /** + * 更新时间. + */ + private Date updated; + + /** + * 数据版本. + */ + private int cpt_version; + + /** + * cpt创建者. + */ + private String publisher; + + /** + * cpt描述. + */ + private String description; + + /** + * cpt对象的json序列化. + */ + private String cpt_schema; + + /** + * cpt签名 + */ + private String cpt_signature; + + /** + * credential验证公钥 + */ + private String credential_publicKey; + + /** + * credential证明 + */ + private String credential_proof; + /** + * claim policies列表 + */ + private String claim_policies; + +} diff --git a/src/main/java/com/webank/weid/suite/persistence/EvidenceValue.java b/src/main/java/com/webank/weid/suite/persistence/EvidenceValue.java new file mode 100644 index 000000000..b27a0ab93 --- /dev/null +++ b/src/main/java/com/webank/weid/suite/persistence/EvidenceValue.java @@ -0,0 +1,54 @@ +package com.webank.weid.suite.persistence; + +import lombok.Data; + +import java.util.Date; + +@Data +public class EvidenceValue { + /** + * 主键,hash. + */ + private String hash; + + /** + * signers of evidence. + */ + private String signers; + + /** + * signatures of evidence. + */ + private String signatures; + + /** + * logs of evidence. + */ + private String logs; + + /** + * 每个签名的时间. + */ + private String updated; + + /** + * revoke of each signature. + */ + private String revoked; + + /** + * extraKey of evidence. + */ + private String extra_key; + + /** + * extraData of evidence. + */ + private String extra_data; + + /** + * groupId of evidence. + */ + private String group_id; + +} diff --git a/src/main/java/com/webank/weid/suite/persistence/Persistence.java b/src/main/java/com/webank/weid/suite/persistence/Persistence.java index 19bffa1e9..ba76fb501 100644 --- a/src/main/java/com/webank/weid/suite/persistence/Persistence.java +++ b/src/main/java/com/webank/weid/suite/persistence/Persistence.java @@ -2,10 +2,14 @@ package com.webank.weid.suite.persistence; +import java.util.List; import java.util.Map; +import com.webank.weid.blockchain.protocol.base.CptBaseInfo; +import com.webank.weid.blockchain.protocol.base.WeIdDocument; +import com.webank.weid.blockchain.protocol.base.WeIdDocumentMetadata; import com.webank.weid.protocol.request.TransactionArgs; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; /** * Data access driver. @@ -78,4 +82,388 @@ public interface Persistence { * @return execute status of the "addTransaction" operation. */ public ResponseData addTransaction(TransactionArgs transactionArgs); + /** + * add data to storage. + * + * @param domain the domain of the data. + * @param weId the key of the data. + * @param documentSchema which you want to store to the storage. + * @return execute status of the "add" operation. + */ + public ResponseData addWeId(String domain, String weId, String documentSchema); + /** + * add data to storage. + * + * @param domain the domain of the data. + * @param weId the key of the data. + * @param documentSchema which you want to store to the storage. + * @return execute status of the "add" operation. + */ + public ResponseData updateWeId(String domain, String weId, String documentSchema); + /** + * query WeIdDocumentMetadata from storage by id. + * + * @param domain the domain of the data. + * @param weId the key of the data. + * @return the data you stored. + */ + public ResponseData getWeIdDocument(String domain, String weId); + /** + * query WeIdDocumentMetadata from storage by id. + * + * @param domain the domain of the data. + * @param weId the key of the data. + * @return the data you stored. + */ + public ResponseData getMeta(String domain, String weId); + + /** + * deactivateWeId by id. + * + * @param domain the domain of the data. + * @param weId the weId you want to deactivate. + * @param state the state you want to change. + * @return execute status of the "update" operation. + */ + public ResponseData deactivateWeId(String domain, String weId, Boolean state); + + /** + * get several weId. + * + * @param domain the domain of the data. + * @param first the first index of weId. + * @param last the last index of weId. + * @return execute status of the "update" operation. + */ + public ResponseData> getWeIdList(String domain, Integer first, Integer last); + + /** + * get total amounts of weId. + * + * @param domain the domain of the data. + * @return execute status of the "update" operation. + */ + public ResponseData getWeIdCount(String domain); + + /** + * query Cpt from storage by cptId. + * + * @param domain the domain of the cpt. + * @param cptId the cptId. + * @return the data you stored. + */ + public ResponseData getCpt(String domain, int cptId); + /** + * save Cpt to storage with cptId. + * + * @param domain the domain of the cpt. + * @param cptId the cptId. + * @param publisher the publisher of the cpt. + * @param description the description of the cpt. + * @param cptSchema the cptSchema of the cpt. + * @param cptSignature the cptSignature of the cpt. + * @return the data you stored. + */ + public ResponseData addCpt(String domain, int cptId, String publisher, String description, String cptSchema, String cptSignature); + /** + * query Policy from storage by policyId. + * + * @param domain the domain of the Policy. + * @param policyId the policyId. + * @return the data you stored. + */ + public ResponseData getPolicy(String domain, int policyId); + /** + * save Policy to storage with policyId. + * + * @param domain the domain of the Policy. + * @param policyId the policyId. + * @param publisher the publisher of the Policy. + * @param description the description of the Policy. + * @param cptSchema the cptSchema of the Policy. + * @param cptSignature the cptSignature of the Policy. + * @return the data you stored. + */ + public ResponseData addPolicy(String domain, int policyId, String publisher, String description, String cptSchema, String cptSignature); + /** + * query presentation from storage by presentationId. + * + * @param domain the domain of the presentation. + * @param presentationId the presentationId. + * @return the data you stored. + */ + public ResponseData getPresentation(String domain, int presentationId); + /** + * save Policy to storage with policyId. + * + * @param domain the domain of the presentation. + * @param presentationId the presentationId. + * @param creator the creator of the presentation. + * @param policies the policies of the presentation. + * @return the data you stored. + */ + public ResponseData addPresentation(String domain, int presentationId, String creator, String policies); + /** + * update Cpt to storage with cptId. + * + * @param domain the domain of the cpt. + * @param cptId the cptId. + * @param cptVersion the cptVersion of the cpt. + * @param publisher the publisher of the cpt. + * @param description the description of the cpt. + * @param cptSchema the cptSchema of the cpt. + * @param cptSignature the cptSignature of the cpt. + * @return the data you stored. + */ + public ResponseData updateCpt(String domain, int cptId, int cptVersion, String publisher, String description, String cptSchema, String cptSignature); + /** + * save Cpt to storage with cptId. + * + * @param domain the domain of the cpt. + * @param cptId the cptId. + * @param credentialPublicKey the publicKey of credential template. + * @param credentialProof the proof of credential template. + * @return the data you stored. + */ + public ResponseData updateCredentialTemplate(String domain, int cptId, String credentialPublicKey, String credentialProof); + /** + * save Cpt to storage with cptId. + * + * @param domain the domain of the cpt. + * @param cptId the cptId. + * @param policies the policy id list. + * @return the data you stored. + */ + public ResponseData updateCptClaimPolicies(String domain, int cptId, String policies); + /** + * get several cptId. + * + * @param domain the domain of the data. + * @param first the first index of cptId. + * @param last the last index of cptId. + * @return execute status of the "update" operation. + */ + public ResponseData> getCptIdList(String domain, Integer first, Integer last); + /** + * get total amounts of cpt. + * + * @param domain the domain of the data. + * @return execute status of the "update" operation. + */ + public ResponseData getCptCount(String domain); + /** + * get several policyId. + * + * @param domain the domain of the data. + * @param first the first index of policyId. + * @param last the last index of policyId. + * @return execute status of the "update" operation. + */ + public ResponseData> getPolicyIdList(String domain, Integer first, Integer last); + /** + * get total amounts of policy. + * + * @param domain the domain of the data. + * @return execute status of the "update" operation. + */ + public ResponseData getPolicyCount(String domain); + /** + * add authority issuer to storage. + * + * @param domain the domain of the data. + * @param weId the key of the data. + * @param name which you want to store to the storage. + * @param desc which you want to store to the storage. + * @param accValue which you want to store to the storage. + * @param extraStr which you want to store to the storage. + * @param extraInt which you want to store to the storage. + * @return execute status of the "add" operation. + */ + public ResponseData addAuthorityIssuer(String domain, String weId, String name, String desc, String accValue, String extraStr, String extraInt); + /** + * remove authority issuer from storage. + * + * @param domain the domain of the data. + * @param weId the key of the data. + * @return execute status of the "add" operation. + */ + public ResponseData removeAuthorityIssuer(String domain, String weId); + + /** + * query authority issuer by weid. + * + * @param domain the domain of the data. + * @param weId the key of the data. + * @return execute status of the "add" operation. + */ + public ResponseData getAuthorityIssuerByWeId(String domain, String weId); + + /** + * query authority issuer by name. + * + * @param domain the domain of the data. + * @param name which you want to store to the storage. + * @return execute status of the "add" operation. + */ + public ResponseData getAuthorityIssuerByName(String domain, String name); + + /** + * updateRole role for weId to storage. + * + * @param domain the domain of the data. + * @param weId the key of the data. + * @param recognize whether recognize or not + * @return execute status of the "add" operation. + */ + public ResponseData updateAuthorityIssuer(String domain, String weId, Integer recognize); + + /** + * get total AuthorityIssuer. + * + * @param domain the domain of the data. + * @return execute status of the "update" operation. + */ + public ResponseData getAuthorityIssuerCount(String domain); + + /** + * get total recognized AuthorityIssuer. + * + * @param domain the domain of the data. + * @return execute status of the "update" operation. + */ + public ResponseData getRecognizedIssuerCount(String domain); + + /** + * add role for weId to storage. + * + * @param domain the domain of the data. + * @param weId the key of the data. + * @param roleValue which kind of role you want to add for weId. + * @return execute status of the "add" operation. + */ + public ResponseData addRole(String domain, String weId, Integer roleValue); + + /** + * query role by weId. + * + * @param domain the domain of the data. + * @param weId the key of the data. + * @return execute status of the "add" operation. + */ + public ResponseData getRole(String domain, String weId); + + /** + * updateRole role for weId to storage. + * + * @param domain the domain of the data. + * @param weId the key of the data. + * @param roleValue which kind of role you want to add for weId. + * @return execute status of the "add" operation. + */ + public ResponseData updateRole(String domain, String weId, Integer roleValue); + + /** + * add SpecificType with typeName to storage. + * + * @param domain the domain of the data. + * @param typeName the typeName of the SpecificType. + * @param owner the owner of the SpecificType + * @return execute status of the "add" operation. + */ + public ResponseData addSpecificType(String domain, String typeName, String owner); + + /** + * query SpecificType by typeName. + * + * @param domain the domain of the data. + * @param typeName the typeName of the SpecificType. + * @return execute status of the "add" operation. + */ + public ResponseData getSpecificType(String domain, String typeName); + + /** + * remove authority issuer from storage. + * + * @param domain the domain of the data. + * @param typeName the key of the data. + * @return execute status of the "add" operation. + */ + public ResponseData removeSpecificType(String domain, String typeName); + + /** + * updateRole role for weId to storage. + * + * @param domain the domain of the data. + * @param typeName the key of the data. + * @param fellow new fellow list of this specific type + * @return execute status of the "add" operation. + */ + public ResponseData updateSpecificTypeFellow(String domain, String typeName, String fellow); + + /** + * get total IssuerType. + * + * @param domain the domain of the data. + * @return execute status of the "update" operation. + */ + public ResponseData getIssuerTypeCount(String domain); + + /** + * get several cptId. + * + * @param domain the domain of the data. + * @param first the first index of cptId. + * @param last the last index of cptId. + * @return execute status of the "update" operation. + */ + public ResponseData> getIssuerTypeList(String domain, Integer first, Integer last); + + /** + * add evidence with hashValue to storage. + * + * @param domain the domain of the data. + * @param hashValue the hashValue of the evidence. + * @param signer the signer of the evidence + * @param signature the signature of the evidence + * @param log the log of the evidence. + * @param updated the updated of the evidence. + * @param revoked the revoked of the evidence. + * @param extraKey the extraKey of the evidence. + * @param group_id the group_id of the evidence. + * @return execute status of the "add" operation. + */ + public ResponseData addEvidenceByHash(String domain, String hashValue, String signer, String signature, String log, String updated, String revoked, String extraKey, String group_id); + + /** + * query evidence by hash. + * + * @param domain the domain of the data. + * @param hash the key of the data. + * @return execute status of the "add" operation. + */ + public ResponseData getEvidenceByHash(String domain, String hash); + + /** + * update evidence with log and signature to storage. + * + * @param domain the domain of the data. + * @param hashValue the hashValue of the evidence. + * @param signer the signer of the evidence. + * @param signature the signature of the evidence + * @param log the log of the evidence. + * @param updated the updated of the evidence. + * @param revoked the revoked of the evidence. + * @param extraKey the revoked of the evidence. + * @return execute status of the "add" operation. + */ + public ResponseData addSignatureAndLogs(String domain, String hashValue, String signer, String signature, String log, String updated, String revoked, String extraKey); + + /** + * query evidence by hash. + * + * @param domain the domain of the data. + * @param extraKey the extraKey of the data. + * @return execute status of the "add" operation. + */ + public ResponseData getEvidenceByExtraKey(String domain, String extraKey); } diff --git a/src/main/java/com/webank/weid/suite/persistence/PersistenceFactory.java b/src/main/java/com/webank/weid/suite/persistence/PersistenceFactory.java index 4923b36be..a3872b4d8 100644 --- a/src/main/java/com/webank/weid/suite/persistence/PersistenceFactory.java +++ b/src/main/java/com/webank/weid/suite/persistence/PersistenceFactory.java @@ -5,7 +5,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.exception.WeIdBaseException; import com.webank.weid.suite.persistence.mysql.driver.MysqlDriver; import com.webank.weid.suite.persistence.redis.driver.RedisDriver; diff --git a/src/main/java/com/webank/weid/suite/persistence/PolicyValue.java b/src/main/java/com/webank/weid/suite/persistence/PolicyValue.java new file mode 100644 index 000000000..7ecc4d680 --- /dev/null +++ b/src/main/java/com/webank/weid/suite/persistence/PolicyValue.java @@ -0,0 +1,62 @@ +package com.webank.weid.suite.persistence; + +import lombok.Data; + +import java.util.Date; + +@Data +public class PolicyValue { + /** + * 主键,cptId. + */ + private int policy_id; + + /** + * 创建时间. + */ + private Date created; + + /** + * 更新时间. + */ + private Date updated; + + /** + * 数据版本. + */ + private int policy_version; + + /** + * cpt创建者. + */ + private String publisher; + + /** + * cpt描述. + */ + private String description; + + /** + * cpt对象的json序列化. + */ + private String policy_schema; + + /** + * cpt签名 + */ + private String policy_signature; + + /** + * credential验证公钥 + */ + private String credential_publicKey; + + /** + * credential证明 + */ + private String credential_proof; + /** + * claim policies列表 + */ + private String claim_policies; +} diff --git a/src/main/java/com/webank/weid/suite/persistence/PresentationValue.java b/src/main/java/com/webank/weid/suite/persistence/PresentationValue.java new file mode 100644 index 000000000..e7883a61a --- /dev/null +++ b/src/main/java/com/webank/weid/suite/persistence/PresentationValue.java @@ -0,0 +1,21 @@ +package com.webank.weid.suite.persistence; + +import lombok.Data; + +@Data +public class PresentationValue { + /** + * 主键,presentationId. + */ + private int presentation_id; + + /** + * presentation创建者. + */ + private String creator; + + /** + * claim policies列表 + */ + private String claim_policies; +} diff --git a/src/main/java/com/webank/weid/suite/persistence/RoleValue.java b/src/main/java/com/webank/weid/suite/persistence/RoleValue.java new file mode 100644 index 000000000..fcecd02e8 --- /dev/null +++ b/src/main/java/com/webank/weid/suite/persistence/RoleValue.java @@ -0,0 +1,38 @@ +package com.webank.weid.suite.persistence; + +import lombok.Data; + +import java.util.Date; + +@Data +public class RoleValue { + /** + * 主键,weid. + */ + private String weid; + + /** + * 创建时间. + */ + private Date created; + + /** + * 更新时间. + */ + private Date updated; + + /** + * 是否是authority_role. + */ + private int authority_role; + + /** + * 是否是committee_role. + */ + private int committee_role; + + /** + * 是否是admin_role. + */ + private int admin_role; +} diff --git a/src/main/java/com/webank/weid/suite/persistence/SpecificTypeValue.java b/src/main/java/com/webank/weid/suite/persistence/SpecificTypeValue.java new file mode 100644 index 000000000..09de68920 --- /dev/null +++ b/src/main/java/com/webank/weid/suite/persistence/SpecificTypeValue.java @@ -0,0 +1,33 @@ +package com.webank.weid.suite.persistence; + +import lombok.Data; + +import java.util.Date; + +@Data +public class SpecificTypeValue { + /** + * 主键,type_name. + */ + private String type_name; + + /** + * SpecificType从属weid. + */ + private String fellow; + + /** + * 创建时间. + */ + private Date created; + + /** + * 更新时间. + */ + private Date updated; + + /** + * SpecificType拥有者. + */ + private String owner; +} diff --git a/src/main/java/com/webank/weid/suite/persistence/WeIdDocumentValue.java b/src/main/java/com/webank/weid/suite/persistence/WeIdDocumentValue.java new file mode 100644 index 000000000..ca673eb65 --- /dev/null +++ b/src/main/java/com/webank/weid/suite/persistence/WeIdDocumentValue.java @@ -0,0 +1,39 @@ +package com.webank.weid.suite.persistence; + +import lombok.Data; + +import java.util.Date; + +@Data +public class WeIdDocumentValue { + /** + * 主键,weid. + */ + private String weid; + + /** + * 创建时间. + */ + private Date created; + + /** + * 更新时间. + */ + private Date updated; + + /** + * 数据版本. + */ + private int version; + + /** + * 是否被注销. + */ + private int deactivated; + + /** + * WeIdDocument对象的json序列化. + */ + private String document_schema; + +} diff --git a/src/main/java/com/webank/weid/suite/persistence/mysql/SqlDomain.java b/src/main/java/com/webank/weid/suite/persistence/mysql/SqlDomain.java index 215052054..de11a7bc2 100644 --- a/src/main/java/com/webank/weid/suite/persistence/mysql/SqlDomain.java +++ b/src/main/java/com/webank/weid/suite/persistence/mysql/SqlDomain.java @@ -8,7 +8,7 @@ import org.slf4j.LoggerFactory; import com.webank.weid.constant.DataDriverConstant; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.exception.WeIdBaseException; import com.webank.weid.suite.persistence.BaseDomain; import com.webank.weid.util.PropertyUtils; @@ -26,7 +26,12 @@ public class SqlDomain extends BaseDomain { /** * the domain prefix. */ - public static final String PREFIX = "domain."; + public static final String DOMAIN_PREFIX = "domain."; + + /** + * the local prefix. + */ + public static final String LOCAL_PREFIX = "local."; /** * 表的默认前缀. diff --git a/src/main/java/com/webank/weid/suite/persistence/mysql/SqlExecutor.java b/src/main/java/com/webank/weid/suite/persistence/mysql/SqlExecutor.java index 8bc1592b5..f50a12c33 100644 --- a/src/main/java/com/webank/weid/suite/persistence/mysql/SqlExecutor.java +++ b/src/main/java/com/webank/weid/suite/persistence/mysql/SqlExecutor.java @@ -9,10 +9,7 @@ import java.sql.SQLException; import java.sql.Timestamp; import java.sql.Types; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.collections4.CollectionUtils; @@ -21,9 +18,9 @@ import org.slf4j.LoggerFactory; import com.webank.weid.constant.DataDriverConstant; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.exception.WeIdBaseException; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; /** @@ -49,23 +46,163 @@ public class SqlExecutor { * sql for add. */ public static final String SQL_SAVE = "insert into $1(id, data, expire, created, updated) " - + "values(?,?,?,?,?)"; + + "values(?,?,?,?,?)"; /** * sql for update. */ public static final String SQL_UPDATE = "update $1 set updated = ?, data = ?, expire = ? " - + "where id = ?"; + + "where id = ?"; /** * sql for delete. */ public static final String SQL_DELETE = "delete from $1 where id = ?"; /** - * sql for add. + * sql for add transaction. */ public static final String SQL_SAVE_TRANSACTION = "insert into weidentity_offline_transaction_info" + "(request_id, transaction_method, transaction_args, transaction_timestamp, extra, batch)" + " values(?,?,?,?,?,?)"; + /** + * sql for query total lines of data. + */ + public static final String SQL_QUERY_TOTAL_LINE = "select COUNT(*) totalCount from $1"; + /** + * sql for query several weId from firstIndex. + */ + public static final String SQL_QUERY_SEVERAL_WEID = "select weid from $1 LIMIT ?, ?"; + /** + * sql for insert weIdDocument and metaDta. + */ + public static final String SQL_SAVE_WEID = "insert into $1 (weid,created,updated,version,deactivated,document_schema) values(?,?,?,?,?,?)"; + /** + * sql for query weIdDocument and metaDta. + */ + public static final String SQL_QUERY_WEID = "select weid,created,updated,version,deactivated,document_schema from $1 where weid=?"; + /** + * sql for update weIdDocument and metaDta. + */ + public static final String SQL_UPDATE_WEID = "update $1 set updated = ?, version = ?, deactivated = ?, document_schema = ? where weid = ?"; + /** + * sql for query cpt. + */ + public static final String SQL_QUERY_CPT = "select cpt_id,created,updated,cpt_version,publisher,description,cpt_schema,cpt_signature,credential_publicKey,credential_proof,claim_policies from $1 where cpt_id =?"; + /** + * sql for insert cpt. + */ + public static final String SQL_SAVE_CPT = "insert into $1 (cpt_id,created,updated,cpt_version,publisher,description,cpt_schema,cpt_signature) values(?,?,?,?,?,?,?,?)"; + /** + * sql for update cpt. + */ + public static final String SQL_UPDATE_CPT = "update $1 set updated = ?, cpt_version = ?, publisher = ?, description = ?, cpt_schema = ?, cpt_signature = ? where cpt_id = ?"; + /** + * sql for update credential template. + */ + public static final String SQL_UPDATE_CREDENTIAL_TEMPLATE = "update $1 set credential_publicKey = ?, credential_proof = ? where cpt_id = ?"; + /** + * sql for update cpt claim policies. + */ + public static final String SQL_UPDATE_CLAIM_POLICIES = "update $1 set claim_policies = ? where cpt_id = ?"; + /** + * sql for query several cpt_id from firstIndex. + */ + public static final String SQL_QUERY_SEVERAL_CPT = "select cpt_id from $1 LIMIT ?, ?"; + /** + * sql for insert policy. + */ + public static final String SQL_SAVE_POLICY = "insert into $1 (policy_id,created,updated,policy_version,publisher,description,policy_schema,policy_signature) values(?,?,?,?,?,?,?,?)"; + /** + * sql for query policy. + */ + public static final String SQL_QUERY_POLICY = "select policy_id,created,updated,policy_version,publisher,description,policy_schema,policy_signature,credential_publicKey,credential_proof,claim_policies from $1 where policy_id =?"; + /** + * sql for query several policy_id from firstIndex. + */ + public static final String SQL_QUERY_SEVERAL_POLICY = "select policy_id from $1 LIMIT ?, ?"; + /** + * sql for insert presentation. + */ + public static final String SQL_SAVE_PRESENTATION = "insert into $1 (presentation_id,creator,claim_policies) values(?,?,?)"; + /** + * sql for query presentation. + */ + public static final String SQL_QUERY_PRESENTATION = "select presentation_id,creator,claim_policies from $1 where presentation_id =?"; + /** + * sql for insert authority issuer. + */ + public static final String SQL_SAVE_AUTHORITY_ISSUER = "insert into $1 (weid,name,description,created,updated,recognize,acc_value,extra_str,extra_int) values(?,?,?,?,?,?,?,?,?)"; + /** + * sql for query authority issuer by weId. + */ + public static final String SQL_QUERY_AUTHORITY_ISSUER_BY_ADDRESS = "select weid,name,description,created,updated,recognize,acc_value,extra_str,extra_int from $1 where weid =?"; + /** + * sql for query authority issuer by name. + */ + public static final String SQL_QUERY_AUTHORITY_ISSUER_BY_NAME = "select weid,name,description,created,updated,recognize,acc_value,extra_str,extra_int from $1 where name =?"; + /** + * sql for delete authority issuer. + */ + public static final String SQL_DELETE_AUTHORITY_ISSUER = "delete from $1 where weid = ?"; + /** + * sql for update authority issuer, only update recognize. + */ + public static final String SQL_UPDATE_AUTHORITY_ISSUER = "update $1 set updated = ?, recognize = ? where weid = ?"; + /** + * sql for query total amount of recognized authority issuer. + */ + public static final String SQL_QUERY_TOTAL_RECOGNIZED_ISSUER = "select COUNT(*) totalCount from $1 where recognize = 1"; + /** + * sql for insert role. + */ + public static final String SQL_SAVE_ROLE = "insert into $1 (weid,created,updated,authority_role,committee_role,admin_role) values(?,?,?,?,?,?)"; + /** + * sql for query role by weId. + */ + public static final String SQL_QUERY_ROLE = "select weid,created,updated,authority_role,committee_role,admin_role from $1 where weid =?"; + /** + * sql for update role. + */ + public static final String SQL_UPDATE_ROLE = "update $1 set updated = ?, authority_role = ?, committee_role = ?, admin_role = ? where weid = ?"; + /** + * sql for insert specific type. + */ + public static final String SQL_SAVE_SPECIFIC_TYPE = "insert into $1 (type_name,created,updated,owner) values(?,?,?,?)"; + /** + * sql for query specific type by type_name. + */ + public static final String SQL_QUERY_SPECIFIC_TYPE = "select type_name,fellow,created,updated,owner from $1 where type_name =?"; + /** + * sql for delete specific type. + */ + public static final String SQL_DELETE_SPECIFIC_TYPE = "delete from $1 where type_name = ?"; + /** + * sql for update specific issuer, only update fellow. + */ + public static final String SQL_UPDATE_SPECIFIC_TYPE_FELLOW = "update $1 set fellow = ? where type_name = ?"; + /** + * sql for query several policy_id from firstIndex. + */ + public static final String SQL_QUERY_SEVERAL_SPECIFIC_TYPE = "select type_name from $1 LIMIT ?, ?"; + /** + * sql for query evidence by hash. + */ + public static final String SQL_QUERY_EVIDENCE_BY_HASH = "select hash,signers,signatures,logs,updated,revoked,extra_key,extra_data,group_id from $1 where hash =?"; + /** + * sql for query evidence by extra_key. + */ + public static final String SQL_QUERY_EVIDENCE_BY_EXTRAKEY = "select hash,signers,signatures,logs,updated,revoked,extra_key,extra_data,group_id from $1 where extra_key =?"; + /** + * sql for insert evidence. + */ + public static final String SQL_SAVE_EVIDENCE_BY_HASH = "insert into $1 (hash,signers,signatures,logs,updated,revoked,group_id) values(?,?,?,?,?,?,?)"; + /** + * sql for insert evidence. + */ + public static final String SQL_SAVE_EVIDENCE_EXTRAKEY = "insert into $1 (hash,signers,signatures,logs,updated,revoked,extra_key,group_id) values(?,?,?,?,?,?,?,?)"; + /** + * sql for update evidence. + */ + public static final String SQL_UPDATE_EVIDENCE = "update $1 set signers = ?, signatures = ?, logs = ?, updated = ?, revoked = ?, extra_key = ? where hash = ?"; private static final Logger logger = LoggerFactory.getLogger(SqlExecutor.class); /** @@ -76,6 +213,7 @@ public class SqlExecutor { * tableDomain 与 tableName的映射. */ private static final Map TABLE_CACHE = new ConcurrentHashMap(); + /** * the sql domain. */ @@ -205,6 +343,101 @@ public ResponseData execute(String sql, Object... data) { return result; } + /** + * 查询操作. + * + * @param sql 需要被执行的SQL语句 + * @param data 占位符所需要的数据 + * @return 返回查询出来的多行数据,每行仅查询一列,仅用于按序号查询多个weid + */ + public ResponseData> executeQueryLines(String sql, Object... data) { + ResponseData> result = new ResponseData>(); + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + try { + conn = ConnectionPool.getConnection(sqlDomain.getBaseDomain()); + if (conn == null) { + return + new ResponseData>( + null, + ErrorCode.PERSISTENCE_GET_CONNECTION_ERROR + ); + } + + ps = conn.prepareStatement(buildExecuteSql(sql, conn)); + for (int i = 0; i < data.length; i++) { + ps.setObject(i + 1, data[i]); + } + + rs = ps.executeQuery(); + List dataList = new ArrayList<>(); + while (rs.next()) { + ResultSetMetaData metaData = rs.getMetaData(); + String columnLabel = metaData.getColumnLabel(1); + dataList.add(rs.getString(columnLabel)); + /*int type = metaData.getColumnType(i); + if (type == Types.TIMESTAMP) { + Timestamp timestamp = rs.getTimestamp(columnLabel); + if (timestamp != null) { + dataMap.put(columnLabel, String.valueOf(timestamp.getTime())); + } + } else { + dataMap.put(columnLabel, rs.getString(columnLabel)); + }*/ + } + rs.close(); + ps.close(); + result.setErrorCode(ErrorCode.SUCCESS); + result.setResult(dataList); + } catch (SQLException e) { + logger.error("Query data from {{}} with exception", sqlDomain.getBaseDomain(), e); + result.setErrorCode(ErrorCode.PERSISTENCE_EXECUTE_FAILED); + } finally { + ConnectionPool.close(conn, ps, rs); + } + return result; + } + + /** + * 查询操作. + * + * @param sql 需要被执行的SQL语句 + * @return 返回查询数据总行数 + */ + public ResponseData executeQueryAmounts(String sql) { + ResponseData result = new ResponseData(); + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + try { + conn = ConnectionPool.getConnection(sqlDomain.getBaseDomain()); + if (conn == null) { + return + new ResponseData( + 0, + ErrorCode.PERSISTENCE_GET_CONNECTION_ERROR + ); + } + ps = conn.prepareStatement(buildExecuteSql(sql, conn)); + rs = ps.executeQuery(); + int rowCount = 0; + if(rs.next()) { + rowCount = rs.getInt("totalCount"); + } + rs.close(); + ps.close(); + result.setErrorCode(ErrorCode.SUCCESS); + result.setResult(rowCount); + } catch (SQLException e) { + logger.error("Query data from {{}} with exception", sqlDomain.getBaseDomain(), e); + result.setErrorCode(ErrorCode.PERSISTENCE_EXECUTE_FAILED); + } finally { + ConnectionPool.close(conn, ps, rs); + } + return result; + } + /** * 批量新增的通用语句. * diff --git a/src/main/java/com/webank/weid/suite/persistence/mysql/driver/MysqlDriver.java b/src/main/java/com/webank/weid/suite/persistence/mysql/driver/MysqlDriver.java index f90740707..63d0e5688 100644 --- a/src/main/java/com/webank/weid/suite/persistence/mysql/driver/MysqlDriver.java +++ b/src/main/java/com/webank/weid/suite/persistence/mysql/driver/MysqlDriver.java @@ -2,21 +2,30 @@ package com.webank.weid.suite.persistence.mysql.driver; +import com.webank.weid.blockchain.protocol.base.AuthorityIssuer; +import com.webank.weid.blockchain.protocol.base.CptBaseInfo; +import com.webank.weid.blockchain.protocol.base.WeIdDocumentMetadata; import com.webank.weid.constant.DataDriverConstant; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; +import com.webank.weid.contract.deploy.AddressProcess; +import com.webank.weid.exception.DatabaseException; import com.webank.weid.exception.WeIdBaseException; +import com.webank.weid.protocol.base.AuthenticationProperty; +import com.webank.weid.blockchain.protocol.base.WeIdDocument; import com.webank.weid.protocol.request.TransactionArgs; -import com.webank.weid.protocol.response.ResponseData; -import com.webank.weid.suite.persistence.Persistence; -import com.webank.weid.suite.persistence.DefaultValue; +import com.webank.weid.blockchain.protocol.response.ResponseData; +import com.webank.weid.service.local.CptServiceLocal; +import com.webank.weid.suite.persistence.*; import com.webank.weid.suite.persistence.mysql.SqlDomain; import com.webank.weid.suite.persistence.mysql.SqlExecutor; import com.webank.weid.util.DataToolUtils; import com.webank.weid.util.PropertyUtils; +import com.webank.weid.util.WeIdUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.*; import java.util.*; /** @@ -52,12 +61,114 @@ public class MysqlDriver implements Persistence { + "PRIMARY KEY (`id`) " + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='the data table'"; + private static final String CREATE_TABLE_WEID_DOCUMENT_SQL = + "CREATE TABLE `$1` (" + + "`weid` varchar(100) NOT NULL UNIQUE COMMENT 'weid'," + + "`created` datetime DEFAULT NULL COMMENT 'created', " + + "`updated` datetime DEFAULT NULL COMMENT 'updated', " + + "`version` int DEFAULT NULL COMMENT 'the document version', " + + "`deactivated` int DEFAULT NULL COMMENT 'deactivated', " + + "`document_schema` blob DEFAULT NULL COMMENT 'json schema of document', " + + "PRIMARY KEY (`weid`) " + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='the weid document table'"; + + private static final String CREATE_TABLE_CPT_SQL = + "CREATE TABLE `$1` (" + + "`cpt_id` int NOT NULL UNIQUE COMMENT 'cpt id'," + + "`created` datetime DEFAULT NULL COMMENT 'created', " + + "`updated` datetime DEFAULT NULL COMMENT 'updated', " + + "`cpt_version` int DEFAULT NULL COMMENT 'the cpt version', " + + "`publisher` varchar(60) DEFAULT NULL COMMENT 'publisher', " + + "`description` varchar(1000) DEFAULT NULL COMMENT 'description of cpt', " + + "`cpt_schema` blob DEFAULT NULL COMMENT 'json schema of cpt', " + + "`cpt_signature` varchar(500) DEFAULT NULL COMMENT 'signature of cpt', " + + "`credential_publicKey` varchar(60) DEFAULT NULL COMMENT 'publicKey of credential template', " + + "`credential_proof` varchar(1000) DEFAULT NULL COMMENT 'proof of credential template', " + + "`claim_policies` varchar(1000) DEFAULT NULL COMMENT 'policy id list', " + + "PRIMARY KEY (`cpt_id`) " + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='the cpt table'"; + + private static final String CREATE_TABLE_POLICY_SQL = + "CREATE TABLE `$1` (" + + "`policy_id` int NOT NULL UNIQUE COMMENT 'policy id'," + + "`created` datetime DEFAULT NULL COMMENT 'created', " + + "`updated` datetime DEFAULT NULL COMMENT 'updated', " + + "`policy_version` int DEFAULT NULL COMMENT 'the policy version', " + + "`publisher` varchar(60) DEFAULT NULL COMMENT 'publisher', " + + "`description` varchar(1000) DEFAULT NULL COMMENT 'description of policy', " + + "`policy_schema` blob DEFAULT NULL COMMENT 'json schema of policy', " + + "`policy_signature` varchar(500) DEFAULT NULL COMMENT 'signature of policy', " + + "`credential_publicKey` varchar(60) DEFAULT NULL COMMENT 'publicKey of credential template', " + + "`credential_proof` varchar(1000) DEFAULT NULL COMMENT 'proof of credential template', " + + "`claim_policies` varchar(1000) DEFAULT NULL COMMENT 'policy id list', " + + "PRIMARY KEY (`policy_id`) " + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='the policy table'"; + + private static final String CREATE_TABLE_PRESENTATION_SQL = + "CREATE TABLE `$1` (" + + "`presentation_id` int NOT NULL UNIQUE COMMENT 'presentation id'," + + "`creator` varchar(60) DEFAULT NULL COMMENT 'creator', " + + "`claim_policies` varchar(1000) DEFAULT NULL COMMENT 'policy id list', " + + "PRIMARY KEY (`presentation_id`) " + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='the presentation table'"; + + private static final String CREATE_TABLE_ROLE_SQL = + "CREATE TABLE `$1` (" + + "`weid` varchar(100) NOT NULL UNIQUE COMMENT 'weid'," + + "`created` datetime DEFAULT NULL COMMENT 'created', " + + "`updated` datetime DEFAULT NULL COMMENT 'updated', " + + "`authority_role` int DEFAULT NULL COMMENT 'the authority role', " + + "`committee_role` int DEFAULT NULL COMMENT 'the committee role', " + + "`admin_role` int DEFAULT NULL COMMENT 'the admin role', " + + "PRIMARY KEY (`weid`) " + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='the role table'"; + + private static final String CREATE_TABLE_AUTHORITY_ISSUER_SQL = + "CREATE TABLE `$1` (" + + "`weid` varchar(100) NOT NULL UNIQUE COMMENT 'weid'," + + "`name` varchar(60) UNIQUE DEFAULT NULL COMMENT 'name'," + + "`description` varchar(1000) DEFAULT NULL COMMENT 'desc'," + + "`created` datetime DEFAULT NULL COMMENT 'created', " + + "`updated` datetime DEFAULT NULL COMMENT 'updated', " + + "`recognize` int DEFAULT NULL COMMENT 'is recognized', " + + "`acc_value` varchar(1000) DEFAULT NULL COMMENT 'the accValue', " + + "`extra_str` blob DEFAULT NULL COMMENT 'the extraStr', " + + "`extra_int` blob DEFAULT NULL COMMENT 'the extraInt', " + + "PRIMARY KEY (`weid`) " + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='the authority issuer table'"; + + private static final String CREATE_TABLE_SPECIFIC_ISSUER_SQL = + "CREATE TABLE `$1` (" + + "`type_name` varchar(60) NOT NULL UNIQUE COMMENT 'specific issuer type name'," + + "`fellow` blob DEFAULT NULL COMMENT 'fellow addresses'," + + "`created` datetime DEFAULT NULL COMMENT 'created', " + + "`updated` datetime DEFAULT NULL COMMENT 'updated', " + + "`owner` varchar(60) DEFAULT NULL COMMENT 'owner'," + + "PRIMARY KEY (`type_name`) " + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='the specific issuer table'"; + + private static final String CREATE_TABLE_EVIDENCE_SQL = + "CREATE TABLE `$1` (" + + "`hash` varchar(100) NOT NULL UNIQUE COMMENT 'hash of evidence'," + + "`signers` blob DEFAULT NULL COMMENT 'signers'," + + "`signatures` blob DEFAULT NULL COMMENT 'signatures', " + + "`logs` blob DEFAULT NULL COMMENT 'logs', " + + "`updated` blob DEFAULT NULL COMMENT 'updated', " + + "`revoked` blob DEFAULT NULL COMMENT 'revoked'," + + "`extra_key` varchar(100) DEFAULT NULL COMMENT 'extraKey of evidence'," + + "`extra_data` blob DEFAULT NULL COMMENT 'extraData of evidence'," + + "`group_id` blob NOT NULL COMMENT 'group_id of evidence'," + + "PRIMARY KEY (`hash`) " + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='the evidence table'"; + private static final Integer FAILED_STATUS = DataDriverConstant.SQL_EXECUTE_FAILED_STATUS; private static final ErrorCode KEY_INVALID = ErrorCode.PRESISTENCE_DATA_KEY_INVALID; private static Boolean isinit = false; + private static int CPT_DEFAULT_VERSION = 1; + /** * the Constructor and init all domain. */ @@ -221,10 +332,66 @@ public ResponseData update(String domain, String id, String data) { */ private void initDomain() { Set domainKeySet = analyzeDomainValue(); + Set localKeySet = analyzeLocalValue(); for (String domainKey : domainKeySet) { SqlExecutor sqlExecutor = new SqlExecutor(new SqlDomain(domainKey)); sqlExecutor.resolveTableDomain(CHECK_TABLE_SQL, CREATE_TABLE_SQL); } + String type = PropertyUtils.getProperty("deploy.style"); + if (type.equals("database")) { + // 初始化表 + for (String localKey : localKeySet) { + SqlExecutor sqlExecutor = new SqlExecutor(new SqlDomain(localKey)); + switch (localKey) { + case "local.weIdDocument" : sqlExecutor.resolveTableDomain(CHECK_TABLE_SQL, CREATE_TABLE_WEID_DOCUMENT_SQL); + case "local.cpt" : sqlExecutor.resolveTableDomain(CHECK_TABLE_SQL, CREATE_TABLE_CPT_SQL); + case "local.policy" : sqlExecutor.resolveTableDomain(CHECK_TABLE_SQL, CREATE_TABLE_POLICY_SQL); + case "local.presentation" : sqlExecutor.resolveTableDomain(CHECK_TABLE_SQL, CREATE_TABLE_PRESENTATION_SQL); + case "local.role" : sqlExecutor.resolveTableDomain(CHECK_TABLE_SQL, CREATE_TABLE_ROLE_SQL); + case "local.authorityIssuer" : sqlExecutor.resolveTableDomain(CHECK_TABLE_SQL, CREATE_TABLE_AUTHORITY_ISSUER_SQL); + case "local.specificIssuer" : sqlExecutor.resolveTableDomain(CHECK_TABLE_SQL, CREATE_TABLE_SPECIFIC_ISSUER_SQL); + case "local.evidence" : sqlExecutor.resolveTableDomain(CHECK_TABLE_SQL, CREATE_TABLE_EVIDENCE_SQL); + } + } + // 初始化管理员权限 + String privateKey = getAddressFromFile("private_key"); + RoleValue result = getRole(DataDriverConstant.LOCAL_ROLE, WeIdUtils.getWeIdFromPrivateKey(privateKey)).getResult(); + if(result == null) { + ResponseData resp = addRole(DataDriverConstant.LOCAL_ROLE, WeIdUtils.getWeIdFromPrivateKey(privateKey), 7); + if (resp.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[initDomain] save admin role to db failed."); + throw new DatabaseException("database error!"); + } + } + } + } + + protected static String getAddressFromFile( + String fileName) { + + BufferedReader br = null; + try { + File file = new File(fileName); + if (file.exists()) { + br = new BufferedReader( + new InputStreamReader(new FileInputStream(file)) + ); + String address = br.readLine(); + return address; + } + } catch (IOException e) { + logger.error("writer file exception", e); + } finally { + if (br != null) { + try { + br.close(); + } catch (IOException e) { + logger.error("io close exception", e); + } + } + } + logger.error("getAddressFromFile() the {} does not exists.", fileName); + return StringUtils.EMPTY; } /** @@ -238,13 +405,31 @@ private Set analyzeDomainValue() { for (Object object : keySet) { String key = String.valueOf(object); if (key.indexOf(SqlDomain.KEY_SPLIT_CHAR) == key.lastIndexOf(SqlDomain.KEY_SPLIT_CHAR) - && key.startsWith(SqlDomain.PREFIX)) { + && key.startsWith(SqlDomain.DOMAIN_PREFIX)) { domainKeySet.add(key); } } return domainKeySet; } + /** + * 分析配置中的local配置, 并且获取对应的配置项key. + * + * @return 返回配置值 + */ + private Set analyzeLocalValue() { + Set keySet = PropertyUtils.getAllPropertyKey(); + Set localKeySet = new HashSet<>(); + for (Object object : keySet) { + String key = String.valueOf(object); + if (key.indexOf(SqlDomain.KEY_SPLIT_CHAR) == key.lastIndexOf(SqlDomain.KEY_SPLIT_CHAR) + && key.startsWith(SqlDomain.LOCAL_PREFIX)) { + localKeySet.add(key); + } + } + return localKeySet; + } + /* (non-Javadoc) * @see com.webank.weid.suite.persistence.Persistence#addOrUpdate(java.lang.String, * java.lang.String, java.lang.String) @@ -289,4 +474,939 @@ public ResponseData addTransaction(TransactionArgs transactionArgs) { return new ResponseData(FAILED_STATUS, e.getErrorCode()); } } + + @Override + public ResponseData addWeId(String domain, String weId, String documentSchema) { + + if (StringUtils.isEmpty(weId)) { + logger.error("[mysql->addWeId] the weId is empty."); + return new ResponseData(FAILED_STATUS, KEY_INVALID); + } + try { + SqlDomain sqlDomain = new SqlDomain(domain); + Date now = sqlDomain.getNow(); + Object[] datas = {weId, now, now, 1, 0, documentSchema}; + return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_SAVE_WEID, datas); + } catch (WeIdBaseException e) { + logger.error("[mysql->addWeId] addWeId error.", e); + return new ResponseData(FAILED_STATUS, e.getErrorCode()); + } + } + + @Override + public ResponseData updateWeId(String domain, String weId, String documentSchema) { + + if (StringUtils.isEmpty(weId)) { + logger.error("[mysql->updateWeId] the weId is empty."); + return new ResponseData(FAILED_STATUS, KEY_INVALID); + } + Date date = new Date(); + try { + SqlDomain sqlDomain = new SqlDomain(domain); + ResponseData> response = new SqlExecutor(sqlDomain) + .executeQuery(SqlExecutor.SQL_QUERY_WEID, weId); + if (response.getErrorCode().intValue() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + WeIdDocumentValue tableData = DataToolUtils.deserialize( + DataToolUtils.serialize(response.getResult()), WeIdDocumentValue.class); + if(tableData.getDeactivated() == 1){ + logger.error("[mysql->updateWeId] the weid is deactivated."); + return new ResponseData<>(FAILED_STATUS, + ErrorCode.WEID_HAS_BEEN_DEACTIVATED); + } + if (StringUtils.isNotBlank(tableData.getDocument_schema())) { + int version = tableData.getVersion(); + version++; + Object[] datas = {date, version, tableData.getDeactivated(), documentSchema, weId}; + return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_UPDATE_WEID, datas); + } + } + return new ResponseData<>(FAILED_STATUS, ErrorCode.getTypeByErrorCode(response.getErrorCode())); + } catch (WeIdBaseException e) { + logger.error("[mysql->updateWeId] update the weid error.", e); + return new ResponseData(FAILED_STATUS, e.getErrorCode()); + } + } + + @Override + public ResponseData getWeIdDocument(String domain, String weId) { + + if (StringUtils.isEmpty(weId)) { + logger.error("[mysql->getWeIdDocument] the weId is empty."); + return new ResponseData<>(null, KEY_INVALID); + } + //String dataKey = DataToolUtils.hash(weId); + try { + SqlDomain sqlDomain = new SqlDomain(domain); + ResponseData> response = new SqlExecutor(sqlDomain) + .executeQuery(SqlExecutor.SQL_QUERY_WEID, weId); + if (response.getErrorCode() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + WeIdDocumentValue tableData = DataToolUtils.deserialize( + DataToolUtils.serialize(response.getResult()), WeIdDocumentValue.class); + if (StringUtils.isNotBlank(tableData.getDocument_schema())) { + return new ResponseData<>(WeIdDocument.fromJson(tableData.getDocument_schema()), ErrorCode.SUCCESS); + } + return new ResponseData<>(null, ErrorCode.WEID_DOES_NOT_EXIST); + } + return new ResponseData<>(null, ErrorCode.WEID_DOES_NOT_EXIST); + } catch (WeIdBaseException e) { + logger.error("[mysql->getWeIdDocument] get the weIdDocument error.", e); + return new ResponseData<>(null, e.getErrorCode()); + } + } + + @Override + public ResponseData getMeta(String domain, String weId) { + + if (StringUtils.isEmpty(weId)) { + logger.error("[mysql->getMeta] the weId is empty."); + return new ResponseData<>(null, KEY_INVALID); + } + //String dataKey = DataToolUtils.hash(weId); + try { + SqlDomain sqlDomain = new SqlDomain(domain); + ResponseData> response = new SqlExecutor(sqlDomain) + .executeQuery(SqlExecutor.SQL_QUERY_WEID, weId); + if (response.getErrorCode() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + WeIdDocumentValue tableData = DataToolUtils.deserialize( + DataToolUtils.serialize(response.getResult()), WeIdDocumentValue.class); + if (StringUtils.isNotBlank(tableData.getDocument_schema())) { + WeIdDocumentMetadata weIdDocumentMetadata = new WeIdDocumentMetadata(); + weIdDocumentMetadata.setCreated(tableData.getCreated().getTime()); + weIdDocumentMetadata.setUpdated(tableData.getUpdated().getTime()); + weIdDocumentMetadata.setVersionId(tableData.getVersion()); + weIdDocumentMetadata.setDeactivated(tableData.getDeactivated() == 1); + return new ResponseData<>(weIdDocumentMetadata, ErrorCode.SUCCESS); + } + return new ResponseData<>(null, ErrorCode.WEID_DOES_NOT_EXIST); + } + return new ResponseData<>(null, ErrorCode.getTypeByErrorCode(response.getErrorCode())); + } catch (WeIdBaseException e) { + logger.error("[mysql->getMeta] getMeta error.", e); + return new ResponseData<>(null, e.getErrorCode()); + } + } + + @Override + public ResponseData deactivateWeId(String domain, String weId, Boolean state) { + + if (StringUtils.isEmpty(weId)) { + logger.error("[mysql->deactivateWeId] the weId is empty."); + return new ResponseData(FAILED_STATUS, KEY_INVALID); + } + String dataKey = DataToolUtils.hash(weId); + Date date = new Date(); + try { + SqlDomain sqlDomain = new SqlDomain(domain); + ResponseData> response = new SqlExecutor(sqlDomain) + .executeQuery(SqlExecutor.SQL_QUERY_WEID, dataKey); + if (response.getErrorCode() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + WeIdDocumentValue tableData = DataToolUtils.deserialize( + DataToolUtils.serialize(response.getResult()), WeIdDocumentValue.class); + if(tableData.getDeactivated() == 1){ + logger.error("[mysql->deactivateWeId] the weid is deactivated."); + return new ResponseData<>(FAILED_STATUS, + ErrorCode.WEID_HAS_BEEN_DEACTIVATED); + } + if (StringUtils.isNotBlank(tableData.getDocument_schema())) { + Object[] datas = {date, tableData.getVersion(), state ? 1:0, tableData.getDocument_schema(), weId}; + return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_UPDATE_WEID, datas); + } + } + return new ResponseData<>(FAILED_STATUS, ErrorCode.getTypeByErrorCode(response.getErrorCode())); + } catch (WeIdBaseException e) { + logger.error("[mysql->deactivateWeId] deactivate the weId error.", e); + return new ResponseData(FAILED_STATUS, e.getErrorCode()); + } + } + + @Override + public ResponseData> getWeIdList(String domain, Integer first, Integer last) { + try { + SqlDomain sqlDomain = new SqlDomain(domain); + Object[] datas = {first, last - first + 1}; + ResponseData> response = new SqlExecutor(sqlDomain) + .executeQueryLines(SqlExecutor.SQL_QUERY_SEVERAL_WEID, datas); + if (response.getErrorCode() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + return new ResponseData<>(response.getResult(), ErrorCode.SUCCESS); + } + return new ResponseData<>(null, ErrorCode.getTypeByErrorCode(response.getErrorCode())); + } catch (WeIdBaseException e) { + logger.error("[mysql->getWeIdList] get the data error.", e); + return new ResponseData<>(null, e.getErrorCode()); + } + } + + @Override + public ResponseData getWeIdCount(String domain) { + try { + SqlDomain sqlDomain = new SqlDomain(domain); + ResponseData response = new SqlExecutor(sqlDomain) + .executeQueryAmounts(SqlExecutor.SQL_QUERY_TOTAL_LINE); + if (response.getErrorCode() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + return new ResponseData<>(response.getResult(), ErrorCode.SUCCESS); + } + return new ResponseData<>(0, ErrorCode.getTypeByErrorCode(response.getErrorCode())); + } catch (WeIdBaseException e) { + logger.error("[mysql->getWeIdCount] get the data error.", e); + return new ResponseData<>(0, e.getErrorCode()); + } + } + + @Override + public ResponseData getCpt(String domain, int cptId) { + + if (cptId<=0) { + logger.error("[mysql->getCpt] the cptId is invalid."); + return new ResponseData(null, KEY_INVALID); + } + try { + ResponseData result = new ResponseData(); + SqlDomain sqlDomain = new SqlDomain(domain); + ResponseData> response = new SqlExecutor(sqlDomain) + .executeQuery(SqlExecutor.SQL_QUERY_CPT, cptId); + if (response.getErrorCode() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + CptValue tableData = DataToolUtils.deserialize( + DataToolUtils.serialize(response.getResult()), CptValue.class); + if (StringUtils.isNotBlank(tableData.getCpt_schema())) { + result.setResult(tableData); + return new ResponseData<>(tableData, ErrorCode.SUCCESS); + } + return new ResponseData<>(null, ErrorCode.CPT_NOT_EXISTS); + } + result.setErrorCode(ErrorCode.getTypeByErrorCode(response.getErrorCode())); + return result; + } catch (WeIdBaseException e) { + logger.error("[mysql->getCpt] getCpt error.", e); + return new ResponseData(null, e.getErrorCode()); + } + } + + @Override + public ResponseData addCpt(String domain, int cptId, String publisher, String description, String cptSchema, String cptSignature) { + + if (cptId<=0) { + logger.error("[mysql->addCpt] the cptId is invalid."); + return new ResponseData(null, KEY_INVALID); + } + try { + SqlDomain sqlDomain = new SqlDomain(domain); + Date now = sqlDomain.getNow(); + Object[] datas = {cptId, now, now, CPT_DEFAULT_VERSION, publisher, description, cptSchema, cptSignature}; + ResponseData result = new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_SAVE_CPT, datas); + if (result.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[addCpt] add Cpt to db failed."); + throw new DatabaseException("database error!"); + } + CptBaseInfo cptBaseInfo = new CptBaseInfo(); + cptBaseInfo.setCptId(cptId); + cptBaseInfo.setCptVersion(CPT_DEFAULT_VERSION); + return new ResponseData<>(cptBaseInfo, ErrorCode.SUCCESS); + } catch (WeIdBaseException e) { + logger.error("[mysql->addCpt] addWeId error.", e); + return new ResponseData(null, e.getErrorCode()); + } + } + + @Override + public ResponseData updateCpt(String domain, int cptId, int cptVersion, String publisher, String description, String cptSchema, String cptSignature) { + + if (cptId<=0) { + logger.error("[mysql->updateCpt] the cptId is invalid."); + return new ResponseData(FAILED_STATUS, KEY_INVALID); + } + try { + SqlDomain sqlDomain = new SqlDomain(domain); + Date now = sqlDomain.getNow(); + Object[] datas = {now, cptVersion, publisher, description, cptSchema, cptSignature, cptId}; + return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_UPDATE_CPT, datas); + } catch (WeIdBaseException e) { + logger.error("[mysql->updateCpt] updateCpt error.", e); + return new ResponseData(FAILED_STATUS, e.getErrorCode()); + } + } + + @Override + public ResponseData> getCptIdList(String domain, Integer first, Integer last) { + try { + SqlDomain sqlDomain = new SqlDomain(domain); + Object[] datas = {first, last - first}; + ResponseData> response = new SqlExecutor(sqlDomain) + .executeQueryLines(SqlExecutor.SQL_QUERY_SEVERAL_CPT, datas); + if (response.getErrorCode() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + List cptList = new ArrayList<>(); + for(int i=0; i(cptList, ErrorCode.SUCCESS); + } + return new ResponseData<>(null, ErrorCode.getTypeByErrorCode(response.getErrorCode())); + } catch (WeIdBaseException e) { + logger.error("[mysql->getCptIdList] get the CptIdList error.", e); + return new ResponseData<>(null, e.getErrorCode()); + } + } + + @Override + public ResponseData getCptCount(String domain) { + try { + SqlDomain sqlDomain = new SqlDomain(domain); + ResponseData response = new SqlExecutor(sqlDomain) + .executeQueryAmounts(SqlExecutor.SQL_QUERY_TOTAL_LINE); + if (response.getErrorCode() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + return new ResponseData<>(response.getResult(), ErrorCode.SUCCESS); + } + return new ResponseData<>(0, ErrorCode.getTypeByErrorCode(response.getErrorCode())); + } catch (WeIdBaseException e) { + logger.error("[mysql->getCptCount] get the count of cpt error.", e); + return new ResponseData<>(0, e.getErrorCode()); + } + } + + @Override + public ResponseData> getPolicyIdList(String domain, Integer first, Integer last) { + try { + SqlDomain sqlDomain = new SqlDomain(domain); + Object[] datas = {first, last - first}; + ResponseData> response = new SqlExecutor(sqlDomain) + .executeQueryLines(SqlExecutor.SQL_QUERY_SEVERAL_POLICY, datas); + if (response.getErrorCode() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + List cptList = new ArrayList<>(); + for(int i=0; i(cptList, ErrorCode.SUCCESS); + } + return new ResponseData<>(null, ErrorCode.getTypeByErrorCode(response.getErrorCode())); + } catch (WeIdBaseException e) { + logger.error("[mysql->getPolicyIdList] get the PolicyIdList error.", e); + return new ResponseData<>(null, e.getErrorCode()); + } + } + + @Override + public ResponseData getPolicyCount(String domain) { + try { + SqlDomain sqlDomain = new SqlDomain(domain); + ResponseData response = new SqlExecutor(sqlDomain) + .executeQueryAmounts(SqlExecutor.SQL_QUERY_TOTAL_LINE); + if (response.getErrorCode() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + return new ResponseData<>(response.getResult(), ErrorCode.SUCCESS); + } + return new ResponseData<>(0, ErrorCode.getTypeByErrorCode(response.getErrorCode())); + } catch (WeIdBaseException e) { + logger.error("[mysql->getPolicyCount] get the count of policy error.", e); + return new ResponseData<>(0, e.getErrorCode()); + } + } + + @Override + public ResponseData updateCredentialTemplate(String domain, int cptId, String credentialPublicKey, String credentialProof) { + + if (cptId<=0) { + logger.error("[mysql->putCredentialTemplate] the cptId is invalid."); + return new ResponseData(FAILED_STATUS, KEY_INVALID); + } + try { + SqlDomain sqlDomain = new SqlDomain(domain); + Date now = sqlDomain.getNow(); + Object[] datas = {credentialPublicKey, credentialProof, cptId}; + return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_UPDATE_CREDENTIAL_TEMPLATE, datas); + } catch (WeIdBaseException e) { + logger.error("[mysql->putCredentialTemplate] updateCpt error.", e); + return new ResponseData(FAILED_STATUS, e.getErrorCode()); + } + } + + @Override + public ResponseData updateCptClaimPolicies(String domain, int cptId, String policies) { + + if (cptId<=0) { + logger.error("[mysql->updateCptClaimPolicies] the cptId is invalid."); + return new ResponseData(FAILED_STATUS, KEY_INVALID); + } + try { + SqlDomain sqlDomain = new SqlDomain(domain); + Date now = sqlDomain.getNow(); + Object[] datas = {policies, cptId}; + return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_UPDATE_CLAIM_POLICIES, datas); + } catch (WeIdBaseException e) { + logger.error("[mysql->updateCptClaimPolicies] updateCptClaimPolicies error.", e); + return new ResponseData(FAILED_STATUS, e.getErrorCode()); + } + } + + @Override + public ResponseData addPolicy(String domain, int policyId, String publisher, String description, String cptSchema, String cptSignature) { + + if (policyId<=0) { + logger.error("[mysql->addPolicy] the policyId is invalid."); + return new ResponseData(null, KEY_INVALID); + } + try { + SqlDomain sqlDomain = new SqlDomain(domain); + Date now = sqlDomain.getNow(); + Object[] datas = {policyId, now, now, CPT_DEFAULT_VERSION, publisher, description, cptSchema, cptSignature}; + ResponseData result = new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_SAVE_POLICY, datas); + if (result.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[addPolicy] add policy to db failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(result.getResult(), ErrorCode.SUCCESS); + } catch (WeIdBaseException e) { + logger.error("[mysql->addPolicy] addPolicy error.", e); + return new ResponseData(null, e.getErrorCode()); + } + } + + @Override + public ResponseData getPolicy(String domain, int policyId) { + //Policy和cpt的表一样,所以可以复用CptValue + if (policyId<=0) { + logger.error("[mysql->getCpt] the cptId is invalid."); + return new ResponseData(null, KEY_INVALID); + } + try { + ResponseData result = new ResponseData(); + SqlDomain sqlDomain = new SqlDomain(domain); + ResponseData> response = new SqlExecutor(sqlDomain) + .executeQuery(SqlExecutor.SQL_QUERY_POLICY, policyId); + if (response.getErrorCode() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + PolicyValue tableData = DataToolUtils.deserialize( + DataToolUtils.serialize(response.getResult()), PolicyValue.class); + if (StringUtils.isNotBlank(tableData.getPolicy_schema())) { + result.setResult(tableData); + return new ResponseData<>(tableData, ErrorCode.SUCCESS); + } + return new ResponseData<>(null, ErrorCode.CPT_NOT_EXISTS); + } + result.setErrorCode(ErrorCode.getTypeByErrorCode(response.getErrorCode())); + return result; + } catch (WeIdBaseException e) { + logger.error("[mysql->getPolicy] getCpt error.", e); + return new ResponseData(null, e.getErrorCode()); + } + } + + @Override + public ResponseData addPresentation(String domain, int presentationId, String creator, String policies) { + + if (presentationId<=0) { + logger.error("[mysql->addPresentation] the presentationId is invalid."); + return new ResponseData(null, KEY_INVALID); + } + try { + SqlDomain sqlDomain = new SqlDomain(domain); + Date now = sqlDomain.getNow(); + Object[] datas = {presentationId, creator, policies}; + ResponseData result = new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_SAVE_PRESENTATION, datas); + if (result.getErrorCode() != ErrorCode.SUCCESS.getCode()) { + logger.error("[addPresentation] add presentation to db failed."); + throw new DatabaseException("database error!"); + } + return new ResponseData<>(result.getResult(), ErrorCode.SUCCESS); + } catch (WeIdBaseException e) { + logger.error("[mysql->addPresentation] addPresentation error.", e); + return new ResponseData(null, e.getErrorCode()); + } + } + + @Override + public ResponseData getPresentation(String domain, int presentationId) { + if (presentationId<=0) { + logger.error("[mysql->getPresentation] the presentationId is invalid."); + return new ResponseData(null, KEY_INVALID); + } + try { + ResponseData result = new ResponseData(); + SqlDomain sqlDomain = new SqlDomain(domain); + ResponseData> response = new SqlExecutor(sqlDomain) + .executeQuery(SqlExecutor.SQL_QUERY_PRESENTATION, presentationId); + if (response.getErrorCode() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + PresentationValue tableData = DataToolUtils.deserialize( + DataToolUtils.serialize(response.getResult()), PresentationValue.class); + if (StringUtils.isNotBlank(tableData.getClaim_policies())) { + result.setResult(tableData); + return new ResponseData<>(tableData, ErrorCode.SUCCESS); + } + return new ResponseData<>(null, ErrorCode.PRESENTATION_POLICY_INVALID); + } + result.setErrorCode(ErrorCode.getTypeByErrorCode(response.getErrorCode())); + return result; + } catch (WeIdBaseException e) { + logger.error("[mysql->getPresentation] getPresentation error.", e); + return new ResponseData(null, e.getErrorCode()); + } + } + + @Override + public ResponseData getAuthorityIssuerByWeId(String domain, String weId) { + + if (StringUtils.isEmpty(weId)) { + logger.error("[mysql->getAuthorityIssuerByWeId] the weId is empty."); + return new ResponseData(null, KEY_INVALID); + } + try { + ResponseData result = new ResponseData(); + SqlDomain sqlDomain = new SqlDomain(domain); + ResponseData> response = new SqlExecutor(sqlDomain) + .executeQuery(SqlExecutor.SQL_QUERY_AUTHORITY_ISSUER_BY_ADDRESS, weId); + if (response.getErrorCode() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + AuthorityIssuerInfo tableData = DataToolUtils.deserialize( + DataToolUtils.serialize(response.getResult()), AuthorityIssuerInfo.class); + if (StringUtils.isNotBlank(tableData.getName())) { + result.setResult(tableData); + return new ResponseData<>(tableData, ErrorCode.SUCCESS); + } + return new ResponseData<>(null, ErrorCode.AUTHORITY_ISSUER_CONTRACT_ERROR_NOT_EXISTS); + } + result.setErrorCode(ErrorCode.getTypeByErrorCode(response.getErrorCode())); + return result; + } catch (WeIdBaseException e) { + logger.error("[mysql->getAuthorityIssuerByWeId] getAuthorityIssuerByWeId error.", e); + return new ResponseData(null, e.getErrorCode()); + } + } + + @Override + public ResponseData getAuthorityIssuerByName(String domain, String name) { + + if (StringUtils.isEmpty(name)) { + logger.error("[mysql->getAuthorityIssuerByName] the name is empty."); + return new ResponseData(null, KEY_INVALID); + } + try { + ResponseData result = new ResponseData(); + SqlDomain sqlDomain = new SqlDomain(domain); + ResponseData> response = new SqlExecutor(sqlDomain) + .executeQuery(SqlExecutor.SQL_QUERY_AUTHORITY_ISSUER_BY_NAME, name); + if (response.getErrorCode() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + AuthorityIssuerInfo tableData = DataToolUtils.deserialize( + DataToolUtils.serialize(response.getResult()), AuthorityIssuerInfo.class); + if (StringUtils.isNotBlank(tableData.getWeid())) { + result.setResult(tableData); + return new ResponseData<>(tableData, ErrorCode.SUCCESS); + } + return new ResponseData<>(null, ErrorCode.AUTHORITY_ISSUER_CONTRACT_ERROR_NOT_EXISTS); + } + result.setErrorCode(ErrorCode.getTypeByErrorCode(response.getErrorCode())); + return result; + } catch (WeIdBaseException e) { + logger.error("[mysql->getAuthorityIssuerByName] getAuthorityIssuerByName error.", e); + return new ResponseData(null, e.getErrorCode()); + } + } + + @Override + public ResponseData addAuthorityIssuer(String domain, String weId, String name, String desc, String accValue, String extraStr, String extraInt) { + if (StringUtils.isEmpty(weId)) { + logger.error("[mysql->addAuthorityIssuer] the weId is empty."); + return new ResponseData(FAILED_STATUS, KEY_INVALID); + } + try { + SqlDomain sqlDomain = new SqlDomain(domain); + Date now = sqlDomain.getNow(); + Object[] datas = {weId, name, desc, now, now, 0, accValue, extraStr, extraInt}; + return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_SAVE_AUTHORITY_ISSUER, datas); + } catch (WeIdBaseException e) { + logger.error("[mysql->addAuthorityIssuer] addAuthorityIssuer error.", e); + return new ResponseData(FAILED_STATUS, e.getErrorCode()); + } + } + + @Override + public ResponseData removeAuthorityIssuer(String domain, String weId) { + if (StringUtils.isEmpty(weId)) { + logger.error("[mysql->removeAuthorityIssuer] the weId is empty."); + return new ResponseData(FAILED_STATUS, KEY_INVALID); + } + try { + SqlDomain sqlDomain = new SqlDomain(domain); + return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_DELETE_AUTHORITY_ISSUER, weId); + } catch (WeIdBaseException e) { + logger.error("[mysql->removeAuthorityIssuer] addAuthorityIssuer error.", e); + return new ResponseData(FAILED_STATUS, e.getErrorCode()); + } + } + + @Override + public ResponseData updateAuthorityIssuer(String domain, String weId, Integer recognize) { + if (StringUtils.isEmpty(weId)) { + logger.error("[mysql->updateAuthorityIssuer] the weId is empty."); + return new ResponseData(FAILED_STATUS, KEY_INVALID); + } + try { + SqlDomain sqlDomain = new SqlDomain(domain); + Date now = sqlDomain.getNow(); + ResponseData> response = new SqlExecutor(sqlDomain) + .executeQuery(SqlExecutor.SQL_QUERY_AUTHORITY_ISSUER_BY_ADDRESS, weId); + if (response.getErrorCode().intValue() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + AuthorityIssuerInfo tableData = DataToolUtils.deserialize( + DataToolUtils.serialize(response.getResult()), AuthorityIssuerInfo.class); + + if (StringUtils.isNotBlank(tableData.getName())) { + return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_UPDATE_AUTHORITY_ISSUER, new Object[]{now, recognize, weId}); + } + } + return new ResponseData<>(FAILED_STATUS, ErrorCode.getTypeByErrorCode(response.getErrorCode())); + } catch (WeIdBaseException e) { + logger.error("[mysql->updateAuthorityIssuer] update the AuthorityIssuer error.", e); + return new ResponseData(FAILED_STATUS, e.getErrorCode()); + } + } + + @Override + public ResponseData getAuthorityIssuerCount(String domain) { + try { + SqlDomain sqlDomain = new SqlDomain(domain); + ResponseData response = new SqlExecutor(sqlDomain) + .executeQueryAmounts(SqlExecutor.SQL_QUERY_TOTAL_LINE); + if (response.getErrorCode() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + return new ResponseData<>(response.getResult(), ErrorCode.SUCCESS); + } + return new ResponseData<>(0, ErrorCode.getTypeByErrorCode(response.getErrorCode())); + } catch (WeIdBaseException e) { + logger.error("[mysql->getAuthorityIssuerCount] get the count of AuthorityIssuer error.", e); + return new ResponseData<>(0, e.getErrorCode()); + } + } + + @Override + public ResponseData getRecognizedIssuerCount(String domain) { + try { + SqlDomain sqlDomain = new SqlDomain(domain); + ResponseData response = new SqlExecutor(sqlDomain) + .executeQueryAmounts(SqlExecutor.SQL_QUERY_TOTAL_RECOGNIZED_ISSUER); + if (response.getErrorCode() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + return new ResponseData<>(response.getResult(), ErrorCode.SUCCESS); + } + return new ResponseData<>(0, ErrorCode.getTypeByErrorCode(response.getErrorCode())); + } catch (WeIdBaseException e) { + logger.error("[mysql->getRecognizedIssuerCount] get the count of recognized authority issuer error.", e); + return new ResponseData<>(0, e.getErrorCode()); + } + } + + @Override + public ResponseData getRole(String domain, String weId) { + + if (StringUtils.isEmpty(weId)) { + logger.error("[mysql->getRole] the weId is empty."); + return new ResponseData(null, KEY_INVALID); + } + try { + ResponseData result = new ResponseData(); + SqlDomain sqlDomain = new SqlDomain(domain); + Date now = sqlDomain.getNow(); + ResponseData> response = new SqlExecutor(sqlDomain) + .executeQuery(SqlExecutor.SQL_QUERY_ROLE, weId); + if (response.getErrorCode() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + RoleValue tableData = DataToolUtils.deserialize( + DataToolUtils.serialize(response.getResult()), RoleValue.class); + if (tableData.getUpdated().before(now)) { + result.setResult(tableData); + return new ResponseData<>(tableData, ErrorCode.SUCCESS); + } + return new ResponseData<>(null, ErrorCode.AUTHORITY_ISSUER_CONTRACT_ERROR_NOT_EXISTS); + } + result.setErrorCode(ErrorCode.getTypeByErrorCode(response.getErrorCode())); + return result; + } catch (WeIdBaseException e) { + logger.error("[mysql->getRole] getRole error.", e); + return new ResponseData(null, e.getErrorCode()); + } + } + + //1 as authority_role, 2 as committee_role, 3 as authority_role & committee_role, 4 as admin_role, 5 as authority_role & admin_role, 6 as committee_role & admin_role, 7 as all role + @Override + public ResponseData addRole(String domain, String weId, Integer roleValue) { + if (StringUtils.isEmpty(weId)) { + logger.error("[mysql->addRole] the weId is empty."); + return new ResponseData(FAILED_STATUS, KEY_INVALID); + } + if (roleValue > 7 || roleValue < 1) { + logger.error("[mysql->addRole] the roleValue is not between 1 and 7."); + return new ResponseData(FAILED_STATUS, KEY_INVALID); + } + try { + SqlDomain sqlDomain = new SqlDomain(domain); + Date now = sqlDomain.getNow(); + switch (roleValue) { + case 1 : return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_SAVE_ROLE, new Object[]{weId, now, now, 1, 0, 0}); + case 2 : return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_SAVE_ROLE, new Object[]{weId, now, now, 0, 1, 0}); + case 3 : return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_SAVE_ROLE, new Object[]{weId, now, now, 1, 1, 0}); + case 4 : return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_SAVE_ROLE, new Object[]{weId, now, now, 0, 0, 1}); + case 5 : return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_SAVE_ROLE, new Object[]{weId, now, now, 1, 0, 1}); + case 6 : return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_SAVE_ROLE, new Object[]{weId, now, now, 0, 1, 1}); + case 7 : return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_SAVE_ROLE, new Object[]{weId, now, now, 1, 1, 1}); + default: return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_SAVE_ROLE, new Object[]{weId, now, now, 0, 0, 0}); + } + } catch (WeIdBaseException e) { + logger.error("[mysql->addRole] addRole error.", e); + return new ResponseData(FAILED_STATUS, e.getErrorCode()); + } + } + + @Override + public ResponseData updateRole(String domain, String weId, Integer roleValue) { + if (StringUtils.isEmpty(weId)) { + logger.error("[mysql->updateRole] the weId is empty."); + return new ResponseData(FAILED_STATUS, KEY_INVALID); + } + if (roleValue > 7 || roleValue < 1) { + logger.error("[mysql->updateRole] the roleValue is not between 1 and 7."); + return new ResponseData(FAILED_STATUS, KEY_INVALID); + } + try { + SqlDomain sqlDomain = new SqlDomain(domain); + Date now = sqlDomain.getNow(); + ResponseData> response = new SqlExecutor(sqlDomain) + .executeQuery(SqlExecutor.SQL_QUERY_ROLE, weId); + if (response.getErrorCode().intValue() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + RoleValue tableData = DataToolUtils.deserialize( + DataToolUtils.serialize(response.getResult()), RoleValue.class); + + if (tableData.getUpdated().before(now)) { + switch (roleValue) { + case 1 : return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_UPDATE_ROLE, new Object[]{now, 0, 1, 0, 0, weId}); + case 2 : return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_UPDATE_ROLE, new Object[]{now, 0, 0, 1, 0, weId}); + case 3 : return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_UPDATE_ROLE, new Object[]{now, 0, 1, 1, 0, weId}); + case 4 : return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_UPDATE_ROLE, new Object[]{now, 0, 0, 0, 1, weId}); + case 5 : return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_UPDATE_ROLE, new Object[]{now, 0, 1, 0, 1, weId}); + case 6 : return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_UPDATE_ROLE, new Object[]{now, 0, 0, 1, 1, weId}); + case 7 : return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_UPDATE_ROLE, new Object[]{now, 0, 1, 1, 1, weId}); + default: return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_UPDATE_ROLE, new Object[]{now, 0, 0, 0, 0, weId}); + } + } + } + return new ResponseData<>(FAILED_STATUS, ErrorCode.getTypeByErrorCode(response.getErrorCode())); + } catch (WeIdBaseException e) { + logger.error("[mysql->updateRole] update the weid error.", e); + return new ResponseData(FAILED_STATUS, e.getErrorCode()); + } + } + + @Override + public ResponseData addSpecificType(String domain, String typeName, String owner) { + if (StringUtils.isEmpty(typeName)) { + logger.error("[mysql->addSpecificType] the typeName is empty."); + return new ResponseData(FAILED_STATUS, KEY_INVALID); + } + try { + SqlDomain sqlDomain = new SqlDomain(domain); + Date now = sqlDomain.getNow(); + Object[] datas = {typeName, now, now, owner}; + return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_SAVE_SPECIFIC_TYPE, datas); + } catch (WeIdBaseException e) { + logger.error("[mysql->addSpecificType] addSpecificType error.", e); + return new ResponseData(FAILED_STATUS, e.getErrorCode()); + } + } + + @Override + public ResponseData removeSpecificType(String domain, String typeName) { + if (StringUtils.isEmpty(typeName)) { + logger.error("[mysql->removeSpecificType] the weId is empty."); + return new ResponseData(FAILED_STATUS, KEY_INVALID); + } + try { + SqlDomain sqlDomain = new SqlDomain(domain); + return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_DELETE_SPECIFIC_TYPE, typeName); + } catch (WeIdBaseException e) { + logger.error("[mysql->removeSpecificType] removeSpecificType error.", e); + return new ResponseData(FAILED_STATUS, e.getErrorCode()); + } + } + + @Override + public ResponseData getSpecificType(String domain, String typeName) { + + if (StringUtils.isEmpty(typeName)) { + logger.error("[mysql->getSpecificType] the typeName is empty."); + return new ResponseData(null, KEY_INVALID); + } + try { + ResponseData result = new ResponseData(); + SqlDomain sqlDomain = new SqlDomain(domain); + Date now = sqlDomain.getNow(); + ResponseData> response = new SqlExecutor(sqlDomain) + .executeQuery(SqlExecutor.SQL_QUERY_SPECIFIC_TYPE, typeName); + if (response.getErrorCode() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + SpecificTypeValue tableData = DataToolUtils.deserialize( + DataToolUtils.serialize(response.getResult()), SpecificTypeValue.class); + if (tableData.getUpdated().before(now)) { + result.setResult(tableData); + return new ResponseData<>(tableData, ErrorCode.SUCCESS); + } + return new ResponseData<>(null, ErrorCode.SPECIFIC_ISSUER_CONTRACT_ERROR_ALREADY_NOT_EXIST); + } + result.setErrorCode(ErrorCode.getTypeByErrorCode(response.getErrorCode())); + return result; + } catch (WeIdBaseException e) { + logger.error("[mysql->getSpecificType] getSpecificType error.", e); + return new ResponseData(null, e.getErrorCode()); + } + } + + @Override + public ResponseData updateSpecificTypeFellow(String domain, String typeName, String fellow) { + try { + SqlDomain sqlDomain = new SqlDomain(domain); + Date now = sqlDomain.getNow(); + Object[] datas = {fellow, typeName}; + return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_UPDATE_SPECIFIC_TYPE_FELLOW, datas); + } catch (WeIdBaseException e) { + logger.error("[mysql->updateSpecificTypeFellow] updateSpecificTypeFellow error.", e); + return new ResponseData(FAILED_STATUS, e.getErrorCode()); + } + } + + @Override + public ResponseData getIssuerTypeCount(String domain) { + try { + SqlDomain sqlDomain = new SqlDomain(domain); + ResponseData response = new SqlExecutor(sqlDomain) + .executeQueryAmounts(SqlExecutor.SQL_QUERY_TOTAL_LINE); + if (response.getErrorCode() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + return new ResponseData<>(response.getResult(), ErrorCode.SUCCESS); + } + return new ResponseData<>(0, ErrorCode.getTypeByErrorCode(response.getErrorCode())); + } catch (WeIdBaseException e) { + logger.error("[mysql->getIssuerTypeCount] get the count of AuthorityIssuer error.", e); + return new ResponseData<>(0, e.getErrorCode()); + } + } + + @Override + public ResponseData> getIssuerTypeList(String domain, Integer first, Integer last) { + try { + SqlDomain sqlDomain = new SqlDomain(domain); + Object[] datas = {first, last - first}; + ResponseData> response = new SqlExecutor(sqlDomain) + .executeQueryLines(SqlExecutor.SQL_QUERY_SEVERAL_SPECIFIC_TYPE, datas); + if (response.getErrorCode() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + return new ResponseData<>(response.getResult(), ErrorCode.SUCCESS); + } + return new ResponseData<>(null, ErrorCode.getTypeByErrorCode(response.getErrorCode())); + } catch (WeIdBaseException e) { + logger.error("[mysql->getIssuerTypeList] get the IssuerTypeList error.", e); + return new ResponseData<>(null, e.getErrorCode()); + } + } + + @Override + public ResponseData getEvidenceByHash(String domain, String hash) { + + if (StringUtils.isEmpty(hash)) { + logger.error("[mysql->getEvidenceByHash] the hash is empty."); + return new ResponseData(null, KEY_INVALID); + } + try { + ResponseData result = new ResponseData(); + SqlDomain sqlDomain = new SqlDomain(domain); + ResponseData> response = new SqlExecutor(sqlDomain) + .executeQuery(SqlExecutor.SQL_QUERY_EVIDENCE_BY_HASH, hash); + if (response.getErrorCode() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + EvidenceValue tableData = DataToolUtils.deserialize( + DataToolUtils.serialize(response.getResult()), EvidenceValue.class); + if (StringUtils.isNotBlank(tableData.getSigners())) { + result.setResult(tableData); + return new ResponseData<>(tableData, ErrorCode.SUCCESS); + } + return new ResponseData<>(null, ErrorCode.CREDENTIAL_EVIDENCE_NOT_EXIST); + } + result.setErrorCode(ErrorCode.getTypeByErrorCode(response.getErrorCode())); + return result; + } catch (WeIdBaseException e) { + logger.error("[mysql->getEvidenceByHash] getEvidenceByHash error.", e); + return new ResponseData(null, e.getErrorCode()); + } + } + + @Override + public ResponseData addEvidenceByHash(String domain, String hashValue, String signer, String signature, String log, String updated, String revoked, String extraKey, String group_id) { + if (StringUtils.isEmpty(hashValue)) { + logger.error("[mysql->addEvidenceByHash] the hashValue is empty."); + return new ResponseData(FAILED_STATUS, KEY_INVALID); + } + try { + SqlDomain sqlDomain = new SqlDomain(domain); + if(extraKey.equals(StringUtils.EMPTY)){ + Object[] datas = {hashValue, signer, signature, log, updated, revoked, group_id}; + return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_SAVE_EVIDENCE_BY_HASH, datas); + } + Object[] datas = {hashValue, signer, signature, log, updated, revoked, extraKey, group_id}; + return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_SAVE_EVIDENCE_EXTRAKEY, datas); + } catch (WeIdBaseException e) { + logger.error("[mysql->addEvidenceByHash] addEvidenceByHash error.", e); + return new ResponseData(FAILED_STATUS, e.getErrorCode()); + } + } + + @Override + public ResponseData addSignatureAndLogs(String domain, String hashValue, String signer, String signature, String log, String updated, String revoked, String extraKey) { + try { + SqlDomain sqlDomain = new SqlDomain(domain); + Date now = sqlDomain.getNow(); + Object[] datas = {signer, signature, log, updated, revoked, extraKey, hashValue}; + return new SqlExecutor(sqlDomain).execute(SqlExecutor.SQL_UPDATE_EVIDENCE, datas); + } catch (WeIdBaseException e) { + logger.error("[mysql->addSignatureAndLogs] addSignatureAndLogs error.", e); + return new ResponseData(FAILED_STATUS, e.getErrorCode()); + } + } + + @Override + public ResponseData getEvidenceByExtraKey(String domain, String extraKey) { + + if (StringUtils.isEmpty(extraKey)) { + logger.error("[mysql->getEvidenceByExtraKey] the hash is empty."); + return new ResponseData(null, KEY_INVALID); + } + try { + ResponseData result = new ResponseData(); + SqlDomain sqlDomain = new SqlDomain(domain); + ResponseData> response = new SqlExecutor(sqlDomain) + .executeQuery(SqlExecutor.SQL_QUERY_EVIDENCE_BY_EXTRAKEY, extraKey); + if (response.getErrorCode() == ErrorCode.SUCCESS.getCode() + && response.getResult() != null) { + EvidenceValue tableData = DataToolUtils.deserialize( + DataToolUtils.serialize(response.getResult()), EvidenceValue.class); + if (StringUtils.isNotBlank(tableData.getSigners())) { + result.setResult(tableData); + return new ResponseData<>(tableData, ErrorCode.SUCCESS); + } + return new ResponseData<>(null, ErrorCode.CREDENTIAL_EVIDENCE_NOT_EXIST); + } + result.setErrorCode(ErrorCode.getTypeByErrorCode(response.getErrorCode())); + return result; + } catch (WeIdBaseException e) { + logger.error("[mysql->getEvidenceByExtraKey] getEvidenceByExtraKey error.", e); + return new ResponseData(null, e.getErrorCode()); + } + } + } diff --git a/src/main/java/com/webank/weid/suite/persistence/redis/RedisDomain.java b/src/main/java/com/webank/weid/suite/persistence/redis/RedisDomain.java index 165e8c10d..0912e9253 100644 --- a/src/main/java/com/webank/weid/suite/persistence/redis/RedisDomain.java +++ b/src/main/java/com/webank/weid/suite/persistence/redis/RedisDomain.java @@ -8,7 +8,7 @@ import org.slf4j.LoggerFactory; import com.webank.weid.constant.DataDriverConstant; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.exception.WeIdBaseException; import com.webank.weid.suite.persistence.BaseDomain; import com.webank.weid.util.PropertyUtils; diff --git a/src/main/java/com/webank/weid/suite/persistence/redis/RedisExecutor.java b/src/main/java/com/webank/weid/suite/persistence/redis/RedisExecutor.java index e315fcb81..7d7dfcc06 100644 --- a/src/main/java/com/webank/weid/suite/persistence/redis/RedisExecutor.java +++ b/src/main/java/com/webank/weid/suite/persistence/redis/RedisExecutor.java @@ -16,9 +16,9 @@ import org.slf4j.LoggerFactory; import com.webank.weid.constant.DataDriverConstant; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.protocol.request.TransactionArgs; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.suite.persistence.DefaultValue; import com.webank.weid.util.DataToolUtils; diff --git a/src/main/java/com/webank/weid/suite/persistence/redis/driver/RedisDriver.java b/src/main/java/com/webank/weid/suite/persistence/redis/driver/RedisDriver.java index 04aa12460..d9f6ca7cc 100644 --- a/src/main/java/com/webank/weid/suite/persistence/redis/driver/RedisDriver.java +++ b/src/main/java/com/webank/weid/suite/persistence/redis/driver/RedisDriver.java @@ -2,13 +2,15 @@ package com.webank.weid.suite.persistence.redis.driver; +import com.webank.weid.blockchain.protocol.base.CptBaseInfo; +import com.webank.weid.blockchain.protocol.base.WeIdDocument; +import com.webank.weid.blockchain.protocol.base.WeIdDocumentMetadata; import com.webank.weid.constant.DataDriverConstant; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.exception.WeIdBaseException; import com.webank.weid.protocol.request.TransactionArgs; -import com.webank.weid.protocol.response.ResponseData; -import com.webank.weid.suite.persistence.Persistence; -import com.webank.weid.suite.persistence.DefaultValue; +import com.webank.weid.blockchain.protocol.response.ResponseData; +import com.webank.weid.suite.persistence.*; import com.webank.weid.suite.persistence.redis.RedisDomain; import com.webank.weid.suite.persistence.redis.RedisExecutor; import com.webank.weid.suite.persistence.redis.RedissonConfig; @@ -223,4 +225,208 @@ public ResponseData addTransaction(TransactionArgs transactionArgs) { return new ResponseData(FAILED_STATUS, e.getErrorCode()); } } + + /* + 以下方法暂不需要,本地部署不需要使用redis方式,默认使用Mysql + */ + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData addWeId(String domain, String weId, String documentSchema) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData updateWeId(String domain, String weId, String documentSchema) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData getWeIdDocument(String domain, String weId) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData getMeta(String domain, String weId) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData deactivateWeId(String domain, String weId, Boolean state) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData> getWeIdList(String domain, Integer first, Integer last) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData getWeIdCount(String domain) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData getCpt(String domain, int cptId) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData addCpt(String domain, int cptId, String publisher, String description, String cptSchema, String cptSignature) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData getPolicy(String domain, int policyId) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData addPolicy(String domain, int policyId, String publisher, String description, String cptSchema, String cptSignature) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData getPresentation(String domain, int presentationId) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData addPresentation(String domain, int presentationId, String creator, String policies) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData updateCpt(String domain, int cptId, int cptVersion, String publisher, String description, String cptSchema, String cptSignature) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData updateCredentialTemplate(String domain, int cptId, String credentialPublicKey, String credentialProof) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData updateCptClaimPolicies(String domain, int cptId, String policies) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData> getCptIdList(String domain, Integer first, Integer last) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData getCptCount(String domain) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData> getPolicyIdList(String domain, Integer first, Integer last) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData getPolicyCount(String domain) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData addAuthorityIssuer(String domain, String weId, String name, String desc, String accValue, String extraStr, String extraInt) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData removeAuthorityIssuer(String domain, String weId) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData getAuthorityIssuerByWeId(String domain, String weId) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData getAuthorityIssuerByName(String domain, String name) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData updateAuthorityIssuer(String domain, String weId, Integer recognize) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData getAuthorityIssuerCount(String domain) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData getRecognizedIssuerCount(String domain) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData addRole(String domain, String weId, Integer roleValue) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData getRole(String domain, String weId) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData updateRole(String domain, String weId, Integer roleValue) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData addSpecificType(String domain, String typeName, String owner) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData getSpecificType(String domain, String typeName) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData removeSpecificType(String domain, String typeName) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData updateSpecificTypeFellow(String domain, String typeName, String fellow) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData getIssuerTypeCount(String domain) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData> getIssuerTypeList(String domain, Integer first, Integer last) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData addEvidenceByHash(String domain, String hashValue, String signer, String signature, String log, String updated, String revoked, String extraKey, String group_id) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData getEvidenceByHash(String domain, String hash) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData addSignatureAndLogs(String domain, String hashValue, String signer, String signature, String log, String updated, String revoked, String extraKey) { + return null; + } + + @Override + public com.webank.weid.blockchain.protocol.response.ResponseData getEvidenceByExtraKey(String domain, String extraKey) { + return null; + } } diff --git a/src/main/java/com/webank/weid/util/BatchTransactionUtils.java b/src/main/java/com/webank/weid/util/BatchTransactionUtils.java index b154ee3fd..84a60ec10 100644 --- a/src/main/java/com/webank/weid/util/BatchTransactionUtils.java +++ b/src/main/java/com/webank/weid/util/BatchTransactionUtils.java @@ -14,11 +14,11 @@ import org.slf4j.LoggerFactory; import com.webank.weid.constant.DataDriverConstant; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.constant.ParamKeyConstant; import com.webank.weid.constant.WeIdConstant; import com.webank.weid.protocol.request.TransactionArgs; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.suite.persistence.PersistenceFactory; import com.webank.weid.suite.persistence.Persistence; import com.webank.weid.suite.persistence.PersistenceType; diff --git a/src/main/java/com/webank/weid/util/CredentialPojoUtils.java b/src/main/java/com/webank/weid/util/CredentialPojoUtils.java index 6f8d2085c..870990e01 100644 --- a/src/main/java/com/webank/weid/util/CredentialPojoUtils.java +++ b/src/main/java/com/webank/weid/util/CredentialPojoUtils.java @@ -8,6 +8,7 @@ import com.webank.weid.protocol.base.*; import com.webank.weid.protocol.request.CreateCredentialPojoArgs; import org.apache.commons.collections4.CollectionUtils; +import com.webank.weid.blockchain.constant.ErrorCode; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/src/main/java/com/webank/weid/util/CredentialUtils.java b/src/main/java/com/webank/weid/util/CredentialUtils.java index dfa00161a..3014e777a 100644 --- a/src/main/java/com/webank/weid/util/CredentialUtils.java +++ b/src/main/java/com/webank/weid/util/CredentialUtils.java @@ -3,6 +3,7 @@ package com.webank.weid.util; import com.webank.weid.constant.*; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.constant.CredentialConstant.CredentialProofType; import com.webank.weid.protocol.base.Credential; import com.webank.weid.protocol.base.CredentialPojo; diff --git a/src/main/java/com/webank/weid/util/DataToolUtils.java b/src/main/java/com/webank/weid/util/DataToolUtils.java index 83638e13e..7bd9d11ec 100644 --- a/src/main/java/com/webank/weid/util/DataToolUtils.java +++ b/src/main/java/com/webank/weid/util/DataToolUtils.java @@ -12,8 +12,8 @@ import com.fasterxml.jackson.databind.type.TypeFactory; import com.networknt.schema.SpecVersion.VersionFlag; import com.networknt.schema.ValidationMessage; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.constant.CredentialConstant; -import com.webank.weid.constant.ErrorCode; import com.webank.weid.constant.JsonSchemaConstant; import com.webank.weid.constant.WeIdConstant; import com.webank.weid.exception.DataTypeCastException; @@ -28,6 +28,12 @@ import org.bouncycastle.util.encoders.Base64; import org.fisco.bcos.sdk.abi.datatypes.generated.Bytes32; import org.fisco.bcos.sdk.abi.datatypes.generated.Uint8; +import org.fisco.bcos.sdk.crypto.CryptoSuite; +import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair; +import org.fisco.bcos.sdk.crypto.signature.ECDSASignatureResult; +import org.fisco.bcos.sdk.crypto.signature.SM2SignatureResult; +import org.fisco.bcos.sdk.crypto.signature.SignatureResult; +import org.fisco.bcos.sdk.model.CryptoType; import org.fisco.bcos.sdk.utils.Numeric; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,8 +45,6 @@ import java.security.SignatureException; import java.util.*; import java.util.regex.Pattern; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; /** * 数据工具类. @@ -85,6 +89,13 @@ public final class DataToolUtils { private static final ObjectWriter OBJECT_WRITER_UN_PRETTY_PRINTER; private static final com.networknt.schema.JsonSchemaFactory JSON_SCHEMA_FACTORY; + + public static final String deployStyle = PropertyUtils.getProperty("deploy.style"); + + //Todo:后面把两个配置文件的cryptoType合成一个,只放在weidentity.properties文件 + public static int cryptoType = Integer.parseInt(PropertyUtils.getProperty("crypto.type")); + + public static final CryptoSuite cryptoSuite = new CryptoSuite(Integer.parseInt(PropertyUtils.getProperty("crypto.type"))); /** * use this to create key pair of v2 or v3 * WARN: create keyPair must use BigInteger of privateKey or decimal String of privateKey @@ -112,6 +123,11 @@ public final class DataToolUtils { //OBJECT_READER = OBJECT_MAPPER.reader(); JSON_SCHEMA_FACTORY = com.networknt.schema.JsonSchemaFactory.getInstance(VersionFlag.V4); + + if (deployStyle.equals("blockchain")) { + cryptoType = com.webank.weid.blockchain.util.DataToolUtils.cryptoType; + } + } /** @@ -128,13 +144,18 @@ public static String getRandomSalt() { } /** - * Keccak-256 hash function. + * Sha 3. * - * @param utfString the utfString - * @return hash value as hex encoded string + * @param input the input + * @return the string */ - public static String hash(String utfString) { - return Numeric.toHexString(hash(utfString.getBytes(StandardCharsets.UTF_8))); + public static String hash(String input) { + if (deployStyle.equals("blockchain")) { + return com.webank.weid.blockchain.util.DataToolUtils.hash(input); + } else { + // default database + return Numeric.toHexString(hash(input.getBytes(StandardCharsets.UTF_8))); + } } /** @@ -144,7 +165,12 @@ public static String hash(String utfString) { * @return the byte[] */ public static byte[] hash(byte[] input) { - return com.webank.weid.blockchain.util.DataToolUtils.hash(input); + if (deployStyle.equals("blockchain")) { + return com.webank.weid.blockchain.util.DataToolUtils.hash(input); + } else { + // default database + return cryptoSuite.hash(input); + } } public static String getHash(String hexInput) { @@ -173,26 +199,6 @@ public static String serialize(T object) { return write.toString(); } - /** - * Convert a private key to its default WeID. - * - * @param privateKey the pass-in privatekey - * @return true if yes, false otherwise - */ - /*public static String convertPrivateKeyToDefaultWeId(BigInteger privateKey) { - return publicKeyStrFromPrivate(privateKey); -// BigInteger publicKey; -// if (encryptType.equals(String.valueOf(EncryptType.ECDSA_TYPE))) { -// publicKey = Sign.publicKeyFromPrivate(new BigInteger(privateKey)); -// } else { -// publicKey = Sign.smPublicKeyFromPrivate(new BigInteger(privateKey)); -// } -// return WeIdUtils -// .convertAddressToWeId(new org.fisco.bcos.web3j.abi.datatypes.Address( -// Keys.getAddress(publicKey)).toString()); -// CryptoKeyPair keyPair = createKeyPairFromPrivate(new BigInteger(privateKey)); -// return WeIdUtils.convertAddressToWeId(keyPair.getAddress()); - }*/ /** * Check whether the String is a valid hash. @@ -511,7 +517,30 @@ public static String cptSchemaToString(CptMapArgs args) { * @return SignatureData for signature value */ public static RsvSignature signToRsvSignature(String rawData, String privateKey) { - return RsvSignature.fromBlockChain(com.webank.weid.blockchain.util.DataToolUtils.signToRsvSignature(rawData, privateKey)); + if (deployStyle.equals("blockchain")) { + return RsvSignature.fromBlockChain(com.webank.weid.blockchain.util.DataToolUtils.signToRsvSignature(rawData, privateKey)); + } else { + // default database + String messageHash = hash(rawData); + return sign(messageHash, privateKey); + } + } + + public static RsvSignature sign(String messageHash, String privateKey) { + CryptoKeyPair cryptoKeyPair = cryptoSuite.getKeyPairFactory().createKeyPair(new BigInteger(privateKey)); + RsvSignature rsvSignature = new RsvSignature(); + SignatureResult signatureResult = cryptoSuite.sign(messageHash, cryptoKeyPair); + Bytes32 R = new Bytes32(signatureResult.getR()); + rsvSignature.setR(R); + Bytes32 S = new Bytes32(signatureResult.getS()); + rsvSignature.setS(S); + if(cryptoSuite.getCryptoTypeConfig() == CryptoType.ECDSA_TYPE){ + ECDSASignatureResult ecdsaSignatureResult = new ECDSASignatureResult(signatureResult.convertToString()); + rsvSignature.setV(new Uint8(BigInteger.valueOf(ecdsaSignatureResult.getV()))); + } else { + rsvSignature.setV(new Uint8(0)); + } + return rsvSignature; } /** @@ -551,25 +580,6 @@ public static RsvSignature SigBase64Deserialization(String signature) { return rsvSignature; } - /** - * De-Serialize secp256k1 signature base64 encoded string, in R, S, V (0, 1) format. - * - * @param signature signature base64 string - * @param publicKey publicKey - * @return secp256k1 signature (v = 0,1) - */ - /*public static SignatureData secp256k1SigBase64Deserialization( - String signature, - BigInteger publicKey) { - byte[] sigBytes = base64Decode(signature.getBytes(StandardCharsets.UTF_8)); - byte[] r = new byte[32]; - byte[] s = new byte[32]; - System.arraycopy(sigBytes, 0, r, 0, 32); - System.arraycopy(sigBytes, 32, s, 0, 32); - - return new SignatureData(sigBytes[64], r, s, Numeric.toBytesPadded(publicKey, 64)); - }*/ - /** * Verify secp256k1 signature. * @@ -583,61 +593,54 @@ public static boolean verifySignature( String signatureBase64, BigInteger publicKey ) { - return com.webank.weid.blockchain.util.DataToolUtils.verifySignature(rawData, signatureBase64, publicKey); - } - - /** - * Recover WeID from message and Signature (Secp256k1 type of sig only). - * - * @param rawData Raw Data - * @param sigBase64 signature in base64 - * @return WeID - */ - /*public static String recoverWeIdFromMsgAndSecp256Sig(String rawData, String sigBase64) { - SignatureData sigData = secp256k1SigBase64Deserialization( - sigBase64); - byte[] hashBytes = Hash.sha3(rawData.getBytes()); - SignatureData modifiedSigData = - new SignatureData( - (byte) (sigData.getV() + 27), - sigData.getR(), - sigData.getS()); - - BigInteger publicKey; - if (encryptType.equals(String.valueOf(EncryptType.ECDSA_TYPE))) { - ECDSASignature sig = - new ECDSASignature( - org.fisco.bcos.web3j.utils.Numeric.toBigInt(modifiedSigData.getR()), - org.fisco.bcos.web3j.utils.Numeric.toBigInt(modifiedSigData.getS())); - publicKey = Sign - .recoverFromSignature(modifiedSigData.getV() - 27, sig, hashBytes); + if (deployStyle.equals("blockchain")) { + return com.webank.weid.blockchain.util.DataToolUtils.verifySignature(rawData, signatureBase64, publicKey); } else { - // not support - throw new WeIdBaseException("not support!"); + // default database + try { + if (rawData == null) { + return false; + } + RsvSignature rsvSignature = SigBase64Deserialization(signatureBase64); + String messageHash = hash(rawData); + return verifySignature(publicKey.toString(16), messageHash, rsvSignature); + } catch (Exception e) { + logger.error("Error occurred during secp256k1 sig verification: {}", e); + return false; + } } - return WeIdUtils.convertPublicKeyToWeId(publicKey.toString(10)); - }*/ + } /** - * Extract the Public Key from the message and the SignatureData. + * Verify secp256k1 signature. * - * @param message the message - * @param signatureData the signature data - * @return publicKey - * @throws SignatureException Signature is the exception. + * @param hexPublicKey publicKey in hex string + * @param messageHash hash of original raw data + * @param rsvSignature signature value + * @return return boolean result, true is success and false is fail */ - /*public static BigInteger signatureToPublicKey( - String message, - Sign.SignatureData signatureData) - throws SignatureException { - try { - return Sign.signedMessageToKey(sha3(message.getBytes(StandardCharsets.UTF_8)), - signatureData); - } catch (Exception e) { - e.printStackTrace(); - throw new SignatureException(e); + public static boolean verifySignature( + String hexPublicKey, + String messageHash, + RsvSignature rsvSignature + ) { + if(cryptoSuite.getCryptoTypeConfig() == CryptoType.ECDSA_TYPE) { + ECDSASignatureResult signatureResult = new ECDSASignatureResult( + rsvSignature.getV().getValue().byteValueExact(), + rsvSignature.getR().getValue(), + rsvSignature.getS().getValue()); + return cryptoSuite.verify(hexPublicKey, messageHash, signatureResult.convertToString()); + } else { +// byte[] sigBytes = new byte[64]; +// System.arraycopy(rsvSignature.getR(), 0, sigBytes, 0, 32); +// System.arraycopy(rsvSignature.getS(), 0, sigBytes, 32, 32); + SM2SignatureResult signatureResult = new SM2SignatureResult( + Numeric.hexStringToByteArray(hexPublicKey), //todo pub of sm2 sig + rsvSignature.getR().getValue(), + rsvSignature.getS().getValue()); + return cryptoSuite.verify(hexPublicKey, messageHash, signatureResult.convertToString()); } - }*/ + } /** * encrypt the data. todo @@ -688,7 +691,12 @@ public static String hexStr2DecStr(String keyInHex) { * @return decimal private key */ public static String generatePrivateKey() { - return com.webank.weid.blockchain.util.DataToolUtils.generatePrivateKey(); + if (deployStyle.equals("blockchain")) { + return com.webank.weid.blockchain.util.DataToolUtils.generatePrivateKey(); + } else { + // default database + return hexStr2DecStr(cryptoSuite.getKeyPairFactory().generateKeyPair().getHexPrivateKey()); + } } /** @@ -708,7 +716,12 @@ public static BigInteger publicKeyFromPrivate(BigInteger privateKey) { * @return publicKey decimal */ public static String publicKeyStrFromPrivate(BigInteger privateKey) { - return com.webank.weid.blockchain.util.DataToolUtils.publicKeyStrFromPrivate(privateKey); + if (deployStyle.equals("blockchain")) { + return com.webank.weid.blockchain.util.DataToolUtils.publicKeyStrFromPrivate(privateKey); + } else { + // default database + return hexStr2DecStr(cryptoSuite.getKeyPairFactory().createKeyPair(privateKey).getHexPublicKey()); + } } /** @@ -718,7 +731,12 @@ public static String publicKeyStrFromPrivate(BigInteger privateKey) { * @return publicKey */ public static String addressFromPrivate(BigInteger privateKey) { - return com.webank.weid.blockchain.util.DataToolUtils.addressFromPrivate(privateKey); + if (deployStyle.equals("blockchain")) { + return com.webank.weid.blockchain.util.DataToolUtils.addressFromPrivate(privateKey); + } else { + // default database + return cryptoSuite.getKeyPairFactory().createKeyPair(privateKey).getAddress(); + } } /** @@ -728,7 +746,12 @@ public static String addressFromPrivate(BigInteger privateKey) { * @return publicKey */ public static String addressFromPublic(BigInteger publicKey) { - return com.webank.weid.blockchain.util.DataToolUtils.addressFromPublic(publicKey); + if (deployStyle.equals("blockchain")) { + return com.webank.weid.blockchain.util.DataToolUtils.addressFromPublic(publicKey); + } else { + // default database + return Numeric.toHexString(cryptoSuite.getKeyPairFactory().getAddress(publicKey)); + } } @@ -762,24 +785,6 @@ public static boolean isValidBase64String(String string) { return org.apache.commons.codec.binary.Base64.isBase64(string); } - /** - * The Serialization class of Signatures. This is simply a concatenation of bytes of the v, r, - * and s. Ethereum uses a similar approach with a wrapping from Base64. - * https://www.programcreek.com/java-api-examples/index.php?source_dir=redPandaj-master/src/org/redPandaLib/crypt/ECKey.java - * uses a DER-formatted serialization, but it does not entail the v tag, henceforth is more - * complex and computation hungry. - * - * @param signatureData the signature data - * @return the byte[] - */ - /*public static byte[] simpleSignatureSerialization(ECDSASignatureResult signatureData) { - byte[] serializedSignatureData = new byte[65]; - serializedSignatureData[0] = signatureData.getV(); - System.arraycopy(signatureData.getR(), 0, serializedSignatureData, 1, 32); - System.arraycopy(signatureData.getS(), 0, serializedSignatureData, 33, 32); - return serializedSignatureData; - }*/ - /** * Verify a signature (base64). * @@ -823,24 +828,6 @@ public static ErrorCode verifySignatureFromWeId( return ErrorCode.SUCCESS; } - /** - * Convert SignatureData to blockchain-ready RSV format. - * - * @param signatureData the signature data - * @return rsvSignature the rsv signature structure - */ - /*public static RsvSignature convertSignatureDataToRsv( - //SignatureData signatureData) { - ECDSASignatureResult signatureData) { - Uint8 v = intToUnt8(Integer.valueOf(signatureData.getV())); - Bytes32 r = bytesArrayToBytes32(signatureData.getR()); - Bytes32 s = bytesArrayToBytes32(signatureData.getS()); - RsvSignature rsvSignature = new RsvSignature(); - rsvSignature.setV(v); - rsvSignature.setR(r); - rsvSignature.setS(s); - return rsvSignature; - }*/ /** * Convert an off-chain Base64 signature String to signatureData format. @@ -864,64 +851,6 @@ public static String getUuId32() { return UUID.randomUUID().toString().replaceAll(SEPARATOR_CHAR, StringUtils.EMPTY); } - /** - * Bytes array to bytes 32. - * - * @param byteValue the byte value - * @return the bytes 32 - */ - public static Bytes32 bytesArrayToBytes32(byte[] byteValue) { - - byte[] byteValueLen32 = new byte[32]; - System.arraycopy(byteValue, 0, byteValueLen32, 0, byteValue.length); - return new Bytes32(byteValueLen32); - } - - /** - * String to bytes 32. - * - * @param string the string - * @return the bytes 32 - */ - public static Bytes32 stringToBytes32(String string) { - - byte[] byteValueLen32 = new byte[32]; - if (StringUtils.isEmpty(string)) { - return new Bytes32(byteValueLen32); - } - byte[] byteValue = string.getBytes(StandardCharsets.UTF_8); - System.arraycopy(byteValue, 0, byteValueLen32, 0, byteValue.length); - - return new Bytes32(byteValueLen32); - } - - /** - * Bytes 32 to bytes array. - * - * @param bytes32 the bytes 32 - * @return the byte[] - */ - public static byte[] bytes32ToBytesArray(Bytes32 bytes32) { - - byte[] bytesArray = new byte[32]; - byte[] bytes32Value = bytes32.getValue(); - System.arraycopy(bytes32Value, 0, bytesArray, 0, 32); - return bytesArray; - } - - /** - * Convert a Byte32 data to Java String. IMPORTANT NOTE: Byte to String is not 1:1 mapped. So - - * Know your data BEFORE do the actual transform! For example, Deximal Bytes, or ASCII Bytes are - * OK to be in Java String, but Encrypted Data, or raw Signature, are NOT OK. - * - * @param bytes32 the bytes 32 - * @return String - */ - public static String bytes32ToString(Bytes32 bytes32) { - - return new String(bytes32.getValue(), StandardCharsets.UTF_8).trim(); - } - /** * convert byte array to string. * @@ -953,61 +882,6 @@ public static byte[] stringToByteArray(String value) { return value.getBytes(StandardCharsets.UTF_8); } - /** - * string to byte32. - * - * @param value stringData - * @return byte[] - */ - public static byte[] stringToByte32Array(String value) { - if (StringUtils.isBlank(value)) { - return new byte[32]; - } - - byte[] bytes = value.getBytes(StandardCharsets.UTF_8); - byte[] newBytes = new byte[32]; - - System.arraycopy(bytes, 0, newBytes, 0, bytes.length); - return newBytes; - } - - /** - * string to byte32List. - * - * @param data stringData - * @param size size of byte32List - * @return data - */ - public static List stringToByte32ArrayList(String data, int size) { - List byteList = new ArrayList<>(); - - if (StringUtils.isBlank(data)) { - for (int i = 0; i < size; i++) { - byteList.add(new byte[32]); - } - return byteList; - } - - byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8); - - if (dataBytes.length <= WeIdConstant.MAX_AUTHORITY_ISSUER_NAME_LENGTH) { - byte[] newBytes = new byte[32]; - System.arraycopy(dataBytes, 0, newBytes, 0, dataBytes.length); - byteList.add(newBytes); - } else { - byteList = splitBytes(dataBytes, size); - } - - if (byteList.size() < size) { - List addList = new ArrayList<>(); - for (int i = 0; i < size - byteList.size(); i++) { - addList.add(new byte[32]); - } - byteList.addAll(addList); - } - return byteList; - } - private static synchronized List splitBytes(byte[] bytes, int size) { List byteList = new ArrayList<>(); double splitLength = @@ -1038,63 +912,6 @@ private static synchronized List splitBytes(byte[] bytes, int size) { return byteList; } - /** - * convert bytesArrayList to Bytes32ArrayList. - * - * @param list byte size - * @param size size - * @return result - */ - public static List bytesArrayListToBytes32ArrayList(List list, int size) { - - List bytesList = new ArrayList<>(); - if (list.isEmpty()) { - for (int i = 0; i < size; i++) { - bytesList.add(new byte[32]); - } - return bytesList; - } - - for (byte[] bytes : list) { - if (bytes.length <= WeIdConstant.MAX_AUTHORITY_ISSUER_NAME_LENGTH) { - byte[] newBytes = new byte[32]; - System.arraycopy(bytes, 0, newBytes, 0, bytes.length); - bytesList.add(newBytes); - } - } - - if (bytesList.size() < size) { - List addList = new ArrayList<>(); - for (int i = 0; i < size - bytesList.size(); i++) { - addList.add(new byte[32]); - } - bytesList.addAll(addList); - } - return bytesList; - } - - /** - * convert list to BigInteger list. - * - * @param list BigInteger list - * @param size size - * @return result - */ - public static List listToListBigInteger(List list, int size) { - List bigIntegerList = new ArrayList<>(); - for (BigInteger bs : list) { - bigIntegerList.add(bs); - } - - List addList = new ArrayList<>(); - if (bigIntegerList.size() < size) { - for (int i = 0; i < size - bigIntegerList.size(); i++) { - addList.add(BigInteger.ZERO); - } - bigIntegerList.addAll(addList); - } - return bigIntegerList; - } /** // * Generate Default CPT Json Schema based on a given CPT ID. @@ -1152,45 +969,6 @@ public static boolean isByteArrayEmpty(byte[] byteArray) { return true; } - /** - * convert byte32List to String. - * - * @param bytesList list - * @param size size - * @return reuslt - */ - public static synchronized String byte32ListToString(List bytesList, int size) { - if (bytesList.isEmpty()) { - return ""; - } - - int zeroCount = 0; - for (int i = 0; i < bytesList.size(); i++) { - for (int j = 0; j < bytesList.get(i).length; j++) { - if (bytesList.get(i)[j] == 0) { - zeroCount++; - } - } - } - - if (WeIdConstant.MAX_AUTHORITY_ISSUER_NAME_LENGTH * size - zeroCount == 0) { - return ""; - } - - byte[] newByte = new byte[WeIdConstant.MAX_AUTHORITY_ISSUER_NAME_LENGTH * size - zeroCount]; - int index = 0; - for (int i = 0; i < bytesList.size(); i++) { - for (int j = 0; j < bytesList.get(i).length; j++) { - if (bytesList.get(i)[j] != 0) { - newByte[index] = bytesList.get(i)[j]; - index++; - } - } - } - - return (new String(newByte)).toString(); - } - /** * Get the current timestamp as the param "created". May be called elsewhere. * diff --git a/src/main/java/com/webank/weid/util/PropertyUtils.java b/src/main/java/com/webank/weid/util/PropertyUtils.java index 1fc8633b0..637340199 100644 --- a/src/main/java/com/webank/weid/util/PropertyUtils.java +++ b/src/main/java/com/webank/weid/util/PropertyUtils.java @@ -80,6 +80,9 @@ private static void load() { try { loadProperties(WEIDENTITY_PROP_NAME); + /*if(getProperty("deploy.style").equals("blockchain")){ + loadProperties(FISCO_PROP_NAME); + }*/ loadProperties(FISCO_PROP_NAME); } catch (IOException e) { logger.error("[PropertyUtils] Load weidentity.properties file failed.", e); diff --git a/src/main/java/com/webank/weid/util/TimestampUtils.java b/src/main/java/com/webank/weid/util/TimestampUtils.java index 4731c4668..455cfd872 100644 --- a/src/main/java/com/webank/weid/util/TimestampUtils.java +++ b/src/main/java/com/webank/weid/util/TimestampUtils.java @@ -16,10 +16,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.protocol.request.timestamp.wesign.GetTimestampRequest; import com.webank.weid.protocol.request.timestamp.wesign.VerifyTimestampRequest; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.protocol.response.timestamp.wesign.AccessTokenResponse; import com.webank.weid.protocol.response.timestamp.wesign.GetTimestampResponse; import com.webank.weid.protocol.response.timestamp.wesign.SignTicketResponse; diff --git a/src/main/java/com/webank/weid/util/WeIdUtils.java b/src/main/java/com/webank/weid/util/WeIdUtils.java index a716ca2b8..027cbb9df 100644 --- a/src/main/java/com/webank/weid/util/WeIdUtils.java +++ b/src/main/java/com/webank/weid/util/WeIdUtils.java @@ -29,7 +29,12 @@ public final class WeIdUtils { private static final Logger logger = LoggerFactory.getLogger(WeIdUtils.class); private static String getChainId() { - return com.webank.weid.blockchain.util.DataToolUtils.chainId; + if (DataToolUtils.deployStyle.equals("blockchain")) { + return com.webank.weid.blockchain.util.DataToolUtils.chainId; + } else { + // default database + return "0"; + } } public static CreateWeIdDataResult createWeId() { diff --git a/src/main/resources/fisco.properties b/src/main/resources/fisco.properties index 85ca516e2..f7e3ef9f2 100644 --- a/src/main/resources/fisco.properties +++ b/src/main/resources/fisco.properties @@ -57,9 +57,9 @@ group.id=1 sdk.sm-crypto=0 # fisco-bcos sdk cert path contains[ca.crt,sdk.crt,sdk.key] # if sdk.sm-crypto is true, contains [gm] directory, and gm dir contains [gmca.crt,gmsdk.crt,gmsdk.key,gmensdk.crt,gmensdk.key] -sdk.cert-path=conf +sdk.cert-path=resources/conf # amop public key of pem and private key of p12 configuration -amop.pub-path=conf/amop/consumer_public_key.pem -amop.pri-path=conf/amop/consumer_private_key.p12 +amop.pub-path=resources/conf/amop/consumer_public_key.pem +amop.pri-path=resources/conf/amop/consumer_private_key.p12 amop.p12-password=123456 \ No newline at end of file diff --git a/src/main/resources/fisco.properties.tpl b/src/main/resources/fisco.properties.tpl index 09952d5cd..e368fa5d2 100644 --- a/src/main/resources/fisco.properties.tpl +++ b/src/main/resources/fisco.properties.tpl @@ -57,9 +57,9 @@ group.id=1 sdk.sm-crypto=${SDK_SM_CRYPTO} # fisco-bcos sdk cert path contains[ca.crt,sdk.crt,sdk.key] # if sdk.sm-crypto is true, contains [gm] directory, and gm dir contains [gmca.crt,gmsdk.crt,gmsdk.key,gmensdk.crt,gmensdk.key] -sdk.cert-path=conf +sdk.cert-path=resources/conf # amop public key of pem and private key of p12 configuration -amop.pub-path=conf/amop/consumer_public_key.pem -amop.pri-path=conf/amop/consumer_private_key.p12 +amop.pub-path=resources/conf/amop/consumer_public_key.pem +amop.pri-path=resources/conf/amop/consumer_private_key.p12 amop.p12-password=123456 diff --git a/src/main/resources/weidentity.properties b/src/main/resources/weidentity.properties index 4e7c25774..d08211653 100644 --- a/src/main/resources/weidentity.properties +++ b/src/main/resources/weidentity.properties @@ -3,8 +3,16 @@ # application config # # # ####################################################################################################### +# Deploy WeIdentity with blockchain or only database +deploy.style=database +# Crypto type, only use for deploy with database, 0 for ECDSA, 1 for SM +crypto.type=0 + # The organization ID for AMOP communication. -blockchain.orgid=org44 +blockchain.orgid=org48 + +# The Blockchain Type +blockchain.type=FISCO_BCOS # The Chain Id chain.id=101 @@ -33,10 +41,10 @@ persistence_type=mysql datasource.name=datasource1 # The configuration of each data source is prefixed by the name of the data source. -datasource1.jdbc.url=jdbc:mysql://10.107.120.121:3306/weidentity?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&rewriteBatchedStatements=true&serverTimezone=Asia/Shanghai +datasource1.jdbc.url=jdbc:mysql://10.107.120.232:3307/weidafee?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&rewriteBatchedStatements=true&serverTimezone=Asia/Shanghai datasource1.jdbc.driver=com.mysql.cj.jdbc.Driver datasource1.jdbc.username=root -datasource1.jdbc.password=Aa12345! +datasource1.jdbc.password=Apps@123 datasource1.jdbc.maxActive=50 datasource1.jdbc.initialSize=5 datasource1.jdbc.minIdle=5 @@ -99,6 +107,15 @@ domain.weIdAuth=datasource1:weid_auth domain.resourceInfo=datasource1:resource_info domain.resourceInfo.timeout=31556908799941 +# tables for running locally +local.weIdDocument=datasource1:table_weid_document +local.cpt=datasource1:table_cpt +local.policy=datasource1:table_policy +local.presentation=datasource1:table_presentation +local.role=datasource1:table_role +local.authorityIssuer=datasource1:table_authority_issuer +local.specificIssuer=datasource1:table_specific_issuer +local.evidence=datasource1:table_evidence ####################################################################################################### # # diff --git a/src/main/resources/weidentity.properties.tpl b/src/main/resources/weidentity.properties.tpl index eb4ad0b9f..57b3571ee 100644 --- a/src/main/resources/weidentity.properties.tpl +++ b/src/main/resources/weidentity.properties.tpl @@ -3,9 +3,17 @@ # application config # # # ####################################################################################################### +# Deploy WeIdentity with blockchain or only database +deploy.style=${DEPLOY_STYLE} +# Crypto type, only use for deploy with database, 0 for ECDSA, 1 for SM +crypto.type=${CRYPTO_TYPE} + # The organization ID for AMOP communication. blockchain.orgid=${ORG_ID} +# The Blockchain Type +blockchain.type=${CHAIN_TYPE} + # The Chain Id chain.id=${CHAIN_ID} @@ -99,6 +107,16 @@ domain.weIdAuth=datasource1:weid_auth domain.resourceInfo=datasource1:resource_info domain.resourceInfo.timeout=31556908799941 +# tables for running locally +local.weIdDocument=datasource1:table_weid_document +local.cpt=datasource1:table_cpt +local.policy=datasource1:table_policy +local.presentation=datasource1:table_presentation +local.role=datasource1:table_role +local.authorityIssuer=datasource1:table_authority_issuer +local.specificIssuer=datasource1:table_specific_issuer +local.evidence=datasource1:table_evidence + ####################################################################################################### # # diff --git a/src/test/java/com/webank/weid/BaseTest.java b/src/test/java/com/webank/weid/BaseTest.java index f03ae563c..0b6977027 100644 --- a/src/test/java/com/webank/weid/BaseTest.java +++ b/src/test/java/com/webank/weid/BaseTest.java @@ -31,7 +31,7 @@ public abstract class BaseTest { static { // mock DB - MockMysqlDriver.mockMysqlDriver(); + //MockMysqlDriver.mockMysqlDriver(); MockIssuerClient.mockMakeCredentialTemplate(); } diff --git a/src/test/java/com/webank/weid/MockMysqlDriver.java b/src/test/java/com/webank/weid/MockMysqlDriver.java index b43c8ce5b..dde21a5dc 100644 --- a/src/test/java/com/webank/weid/MockMysqlDriver.java +++ b/src/test/java/com/webank/weid/MockMysqlDriver.java @@ -12,8 +12,8 @@ import org.apache.commons.collections4.CollectionUtils; import com.webank.weid.constant.DataDriverConstant; -import com.webank.weid.constant.ErrorCode; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.constant.ErrorCode; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.suite.persistence.mysql.SqlDomain; import com.webank.weid.suite.persistence.mysql.SqlExecutor; diff --git a/src/test/java/com/webank/weid/full/TestBaseService.java b/src/test/java/com/webank/weid/full/TestBaseService.java index 910873369..40fb6a3c4 100644 --- a/src/test/java/com/webank/weid/full/TestBaseService.java +++ b/src/test/java/com/webank/weid/full/TestBaseService.java @@ -23,7 +23,7 @@ import com.webank.weid.BaseTest; import com.webank.weid.common.LogUtil; import com.webank.weid.common.PasswordKey; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.protocol.base.ClaimPolicy; import com.webank.weid.protocol.base.CptBaseInfo; import com.webank.weid.protocol.base.Credential; @@ -40,7 +40,7 @@ import com.webank.weid.protocol.request.RegisterAuthorityIssuerArgs; import com.webank.weid.protocol.request.ServiceArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.util.CredentialUtils; import com.webank.weid.util.WeIdUtils; diff --git a/src/test/java/com/webank/weid/full/auth/TestAddIssuerIntoIssuerType.java b/src/test/java/com/webank/weid/full/auth/TestAddIssuerIntoIssuerType.java index 5f8716768..477026387 100644 --- a/src/test/java/com/webank/weid/full/auth/TestAddIssuerIntoIssuerType.java +++ b/src/test/java/com/webank/weid/full/auth/TestAddIssuerIntoIssuerType.java @@ -1,19 +1,20 @@ package com.webank.weid.full.auth; +import com.webank.weid.util.WeIdUtils; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.WeIdAuthentication; import com.webank.weid.protocol.base.WeIdPrivateKey; import com.webank.weid.protocol.request.RemoveAuthorityIssuerArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; public class TestAddIssuerIntoIssuerType extends TestBaseService { diff --git a/src/test/java/com/webank/weid/full/auth/TestGetAllAuthorityIssuerList.java b/src/test/java/com/webank/weid/full/auth/TestGetAllAuthorityIssuerList.java index bb5ce3197..d2e89ef22 100644 --- a/src/test/java/com/webank/weid/full/auth/TestGetAllAuthorityIssuerList.java +++ b/src/test/java/com/webank/weid/full/auth/TestGetAllAuthorityIssuerList.java @@ -13,13 +13,13 @@ import org.slf4j.LoggerFactory; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.protocol.base.AuthorityIssuer; import com.webank.weid.protocol.base.WeIdPrivateKey; import com.webank.weid.protocol.request.RemoveAuthorityIssuerArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.util.DataToolUtils; diff --git a/src/test/java/com/webank/weid/full/auth/TestIsAuthorityIssuer.java b/src/test/java/com/webank/weid/full/auth/TestIsAuthorityIssuer.java index 1ec5f4743..55c1d74a7 100644 --- a/src/test/java/com/webank/weid/full/auth/TestIsAuthorityIssuer.java +++ b/src/test/java/com/webank/weid/full/auth/TestIsAuthorityIssuer.java @@ -9,14 +9,14 @@ import org.slf4j.LoggerFactory; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.AuthorityIssuer; import com.webank.weid.protocol.base.WeIdPrivateKey; import com.webank.weid.protocol.request.RemoveAuthorityIssuerArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import java.math.BigInteger; @@ -180,7 +180,7 @@ public void testIsAuthorityIssuerWeIdNotRegister() { .isAuthorityIssuer(weId); LogUtil.info(logger, "isAuthorityIssuer", response); - Assert.assertEquals(ErrorCode.AUTHORITY_ISSUER_CONTRACT_ERROR_NOT_EXISTS.getCode(), + Assert.assertEquals(ErrorCode.SUCCESS.getCode(), response.getErrorCode().intValue()); Assert.assertEquals(false, response.getResult()); } @@ -195,7 +195,7 @@ public void testIsAuthorityIssuerWeIdNotExist() { .isAuthorityIssuer("did:weid:0x5f3d8234e93823fac7ebdf0cfaa03b6a43d87733"); LogUtil.info(logger, "isAuthorityIssuer", response); - Assert.assertEquals(ErrorCode.AUTHORITY_ISSUER_CONTRACT_ERROR_NOT_EXISTS.getCode(), + Assert.assertEquals(ErrorCode.SUCCESS.getCode(), response.getErrorCode().intValue()); Assert.assertEquals(false, response.getResult()); } @@ -222,7 +222,7 @@ public void testIsAuthorityIssuerRemovedWeId() { response = authorityIssuerService.isAuthorityIssuer(createWeId.getWeId()); LogUtil.info(logger, "isAuthorityIssuer", response); - Assert.assertEquals(ErrorCode.AUTHORITY_ISSUER_CONTRACT_ERROR_NOT_EXISTS.getCode(), + Assert.assertEquals(ErrorCode.SUCCESS.getCode(), response.getErrorCode().intValue()); Assert.assertEquals(false, response.getResult()); } diff --git a/src/test/java/com/webank/weid/full/auth/TestQueryAuthorityIssuerInfo.java b/src/test/java/com/webank/weid/full/auth/TestQueryAuthorityIssuerInfo.java index 8ea9173ee..094f77e4d 100644 --- a/src/test/java/com/webank/weid/full/auth/TestQueryAuthorityIssuerInfo.java +++ b/src/test/java/com/webank/weid/full/auth/TestQueryAuthorityIssuerInfo.java @@ -8,7 +8,7 @@ import org.slf4j.LoggerFactory; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.AuthorityIssuer; @@ -16,7 +16,7 @@ import com.webank.weid.protocol.request.RegisterAuthorityIssuerArgs; import com.webank.weid.protocol.request.RemoveAuthorityIssuerArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.util.DateUtils; /** diff --git a/src/test/java/com/webank/weid/full/auth/TestRegisterAuthorityIssuer.java b/src/test/java/com/webank/weid/full/auth/TestRegisterAuthorityIssuer.java index 63baed2a9..ed5e392c8 100644 --- a/src/test/java/com/webank/weid/full/auth/TestRegisterAuthorityIssuer.java +++ b/src/test/java/com/webank/weid/full/auth/TestRegisterAuthorityIssuer.java @@ -3,14 +3,14 @@ package com.webank.weid.full.auth; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.AuthorityIssuer; import com.webank.weid.protocol.base.WeIdPrivateKey; import com.webank.weid.protocol.request.RegisterAuthorityIssuerArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.util.DateUtils; import org.junit.Assert; import org.junit.Test; diff --git a/src/test/java/com/webank/weid/full/auth/TestRegisterIssuerType.java b/src/test/java/com/webank/weid/full/auth/TestRegisterIssuerType.java index e46876187..996162517 100644 --- a/src/test/java/com/webank/weid/full/auth/TestRegisterIssuerType.java +++ b/src/test/java/com/webank/weid/full/auth/TestRegisterIssuerType.java @@ -10,13 +10,13 @@ import org.slf4j.LoggerFactory; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.IssuerType; import com.webank.weid.protocol.base.WeIdAuthentication; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; /** * testing basic method classes. diff --git a/src/test/java/com/webank/weid/full/auth/TestRemoveAuthorityIssuer.java b/src/test/java/com/webank/weid/full/auth/TestRemoveAuthorityIssuer.java index 6b46425ec..a3a672798 100644 --- a/src/test/java/com/webank/weid/full/auth/TestRemoveAuthorityIssuer.java +++ b/src/test/java/com/webank/weid/full/auth/TestRemoveAuthorityIssuer.java @@ -8,14 +8,14 @@ import org.slf4j.LoggerFactory; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.WeIdPrivateKey; import com.webank.weid.protocol.request.RegisterAuthorityIssuerArgs; import com.webank.weid.protocol.request.RemoveAuthorityIssuerArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; /** * removeAuthorityIssuer method for testing AuthorityIssuerService. diff --git a/src/test/java/com/webank/weid/full/auth/TestRemoveIssuerFromIssuerType.java b/src/test/java/com/webank/weid/full/auth/TestRemoveIssuerFromIssuerType.java index cab94705b..9ef73bc50 100644 --- a/src/test/java/com/webank/weid/full/auth/TestRemoveIssuerFromIssuerType.java +++ b/src/test/java/com/webank/weid/full/auth/TestRemoveIssuerFromIssuerType.java @@ -8,13 +8,13 @@ import org.slf4j.LoggerFactory; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.WeIdAuthentication; import com.webank.weid.protocol.base.WeIdPrivateKey; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; public class TestRemoveIssuerFromIssuerType extends TestBaseService { @@ -160,7 +160,7 @@ public void testRemoveIssuerFromIssuerType_issuerTypeNotRegister() { callerAuth, "中国人民-chinese people", issuer.getWeId()); LogUtil.info(logger, "removeIssuerFromIssuerType", response); - Assert.assertEquals(ErrorCode.SPECIFIC_ISSUER_CONTRACT_ERROR_NOT_EXIST.getCode(), + Assert.assertEquals(ErrorCode.SPECIFIC_ISSUER_CONTRACT_ERROR_ALREADY_NOT_EXIST.getCode(), response.getErrorCode().intValue()); Assert.assertFalse(response.getResult()); @@ -207,7 +207,7 @@ public void testRemoveIssuerFromIssuerType_issuerNotInIssuerType() { callerAuth, issuerType, createWeIdData.getWeId()); LogUtil.info(logger, "removeIssuerFromIssuerType", response); - Assert.assertEquals(ErrorCode.SPECIFIC_ISSUER_CONTRACT_ERROR_NOT_EXIST.getCode(), + Assert.assertEquals(ErrorCode.SPECIFIC_ISSUER_CONTRACT_ERROR_ALREADY_NOT_EXIST.getCode(), response.getErrorCode().intValue()); Assert.assertFalse(response.getResult()); } diff --git a/src/test/java/com/webank/weid/full/auth/TestSpecificIssuer.java b/src/test/java/com/webank/weid/full/auth/TestSpecificIssuer.java index ede5035ff..aca1260f4 100644 --- a/src/test/java/com/webank/weid/full/auth/TestSpecificIssuer.java +++ b/src/test/java/com/webank/weid/full/auth/TestSpecificIssuer.java @@ -7,14 +7,14 @@ import org.junit.Assert; import org.junit.Test; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.constant.WeIdConstant; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.WeIdAuthentication; import com.webank.weid.protocol.base.WeIdPrivateKey; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; /** * Test most cases of Specific Issuers. @@ -101,8 +101,8 @@ public void integrationSpecificIssuerListTest() { ResponseData> respData3 = authorityIssuerService .getAllSpecificTypeIssuerList(defaultType, 0, WeIdConstant.MAX_AUTHORITY_ISSUER_LIST_SIZE); - Assert.assertNotNull(respData2.getResult()); - Assert.assertEquals(respData2.getResult().size(), 0); + Assert.assertNull(respData2.getResult()); + //Assert.assertEquals(respData2.getResult().size(), 0); Assert.assertNotNull(respData3.getResult()); Assert.assertTrue(respData3.getResult().size() > 0); ResponseData response4 = authorityIssuerService diff --git a/src/test/java/com/webank/weid/full/cpt/TestPolicyServices.java b/src/test/java/com/webank/weid/full/cpt/TestPolicyServices.java index 6ab7a3627..2933d126a 100644 --- a/src/test/java/com/webank/weid/full/cpt/TestPolicyServices.java +++ b/src/test/java/com/webank/weid/full/cpt/TestPolicyServices.java @@ -15,7 +15,7 @@ import com.webank.weid.protocol.base.PresentationPolicyE; import com.webank.weid.protocol.base.WeIdAuthentication; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.util.DataToolUtils; /** diff --git a/src/test/java/com/webank/weid/full/cpt/TestQueryCpt.java b/src/test/java/com/webank/weid/full/cpt/TestQueryCpt.java index 93d58b8a2..b5e1b0410 100644 --- a/src/test/java/com/webank/weid/full/cpt/TestQueryCpt.java +++ b/src/test/java/com/webank/weid/full/cpt/TestQueryCpt.java @@ -8,13 +8,13 @@ import org.slf4j.LoggerFactory; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.Cpt; import com.webank.weid.protocol.base.CptBaseInfo; import com.webank.weid.protocol.request.CptMapArgs; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; /** * queryCpt method for testing CptService. diff --git a/src/test/java/com/webank/weid/full/cpt/TestRegisterCptArgs.java b/src/test/java/com/webank/weid/full/cpt/TestRegisterCptArgs.java index 70915556e..d9bd0ff53 100644 --- a/src/test/java/com/webank/weid/full/cpt/TestRegisterCptArgs.java +++ b/src/test/java/com/webank/weid/full/cpt/TestRegisterCptArgs.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.webank.weid.common.LogUtil; import com.webank.weid.common.PasswordKey; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.constant.JsonSchemaConstant; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; @@ -16,7 +16,7 @@ import com.webank.weid.protocol.request.CptMapArgs; import com.webank.weid.protocol.request.CptStringArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.util.WeIdUtils; import org.junit.Assert; import org.junit.Test; diff --git a/src/test/java/com/webank/weid/full/cpt/TestRegisterCptArgsWithId.java b/src/test/java/com/webank/weid/full/cpt/TestRegisterCptArgsWithId.java index b6b360e31..a00084ba2 100644 --- a/src/test/java/com/webank/weid/full/cpt/TestRegisterCptArgsWithId.java +++ b/src/test/java/com/webank/weid/full/cpt/TestRegisterCptArgsWithId.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.webank.weid.common.LogUtil; import com.webank.weid.common.PasswordKey; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.constant.JsonSchemaConstant; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; @@ -15,7 +15,7 @@ import com.webank.weid.protocol.request.CptMapArgs; import com.webank.weid.protocol.request.CptStringArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.util.WeIdUtils; import org.junit.Assert; import org.junit.Test; diff --git a/src/test/java/com/webank/weid/full/cpt/TestRegisterCptStringArgs.java b/src/test/java/com/webank/weid/full/cpt/TestRegisterCptStringArgs.java index c4ebf2b9b..d8422adeb 100644 --- a/src/test/java/com/webank/weid/full/cpt/TestRegisterCptStringArgs.java +++ b/src/test/java/com/webank/weid/full/cpt/TestRegisterCptStringArgs.java @@ -8,7 +8,7 @@ import org.slf4j.LoggerFactory; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.Cpt; @@ -16,7 +16,7 @@ import com.webank.weid.protocol.base.WeIdPrivateKey; import com.webank.weid.protocol.request.CptStringArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; public class TestRegisterCptStringArgs extends TestBaseService { diff --git a/src/test/java/com/webank/weid/full/cpt/TestRegisterCptStringArgsWithId.java b/src/test/java/com/webank/weid/full/cpt/TestRegisterCptStringArgsWithId.java index f9a659785..31845440e 100644 --- a/src/test/java/com/webank/weid/full/cpt/TestRegisterCptStringArgsWithId.java +++ b/src/test/java/com/webank/weid/full/cpt/TestRegisterCptStringArgsWithId.java @@ -8,7 +8,7 @@ import org.slf4j.LoggerFactory; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.Cpt; @@ -16,7 +16,7 @@ import com.webank.weid.protocol.base.WeIdPrivateKey; import com.webank.weid.protocol.request.CptStringArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; public class TestRegisterCptStringArgsWithId extends TestBaseService { diff --git a/src/test/java/com/webank/weid/full/cpt/TestUpdateCpt.java b/src/test/java/com/webank/weid/full/cpt/TestUpdateCpt.java index d7473a0fb..7ecdf0db2 100644 --- a/src/test/java/com/webank/weid/full/cpt/TestUpdateCpt.java +++ b/src/test/java/com/webank/weid/full/cpt/TestUpdateCpt.java @@ -13,7 +13,7 @@ import com.webank.weid.common.LogUtil; import com.webank.weid.common.PasswordKey; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.constant.JsonSchemaConstant; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; @@ -23,7 +23,7 @@ import com.webank.weid.protocol.request.CptMapArgs; import com.webank.weid.protocol.request.CptStringArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.util.WeIdUtils; /** @@ -218,7 +218,7 @@ public void testUpdateCpt_cptIdNotExist() { LogUtil.info(logger, "updateCpt", response); Assert.assertEquals( - ErrorCode.CPT_NO_PERMISSION.getCode(), + ErrorCode.CPT_NOT_EXISTS.getCode(), response.getErrorCode().intValue() ); Assert.assertNull(response.getResult()); diff --git a/src/test/java/com/webank/weid/full/credential/TestCreateCredential.java b/src/test/java/com/webank/weid/full/credential/TestCreateCredential.java index 19aeab8fb..85512e4e2 100644 --- a/src/test/java/com/webank/weid/full/credential/TestCreateCredential.java +++ b/src/test/java/com/webank/weid/full/credential/TestCreateCredential.java @@ -13,7 +13,7 @@ import com.webank.weid.common.LogUtil; import com.webank.weid.constant.CredentialConstant; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.CptBaseInfo; @@ -22,7 +22,7 @@ import com.webank.weid.protocol.base.WeIdPrivateKey; import com.webank.weid.protocol.request.CreateCredentialArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.util.DataToolUtils; import com.webank.weid.util.DateUtils; diff --git a/src/test/java/com/webank/weid/full/credential/TestGetCredentialHash.java b/src/test/java/com/webank/weid/full/credential/TestGetCredentialHash.java index cdddb5e2d..db3e5a9fc 100644 --- a/src/test/java/com/webank/weid/full/credential/TestGetCredentialHash.java +++ b/src/test/java/com/webank/weid/full/credential/TestGetCredentialHash.java @@ -11,11 +11,11 @@ import org.junit.Test; import com.webank.weid.constant.CredentialConstant.CredentialProofType; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.constant.ParamKeyConstant; import com.webank.weid.full.TestBaseService; import com.webank.weid.protocol.base.Credential; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; public class TestGetCredentialHash extends TestBaseService { diff --git a/src/test/java/com/webank/weid/full/credential/TestGetCredentialJson.java b/src/test/java/com/webank/weid/full/credential/TestGetCredentialJson.java index 3e6cd616a..90d57fb39 100644 --- a/src/test/java/com/webank/weid/full/credential/TestGetCredentialJson.java +++ b/src/test/java/com/webank/weid/full/credential/TestGetCredentialJson.java @@ -12,11 +12,11 @@ import com.webank.weid.constant.CredentialConstant; import com.webank.weid.constant.CredentialConstant.CredentialProofType; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.constant.ParamKeyConstant; import com.webank.weid.full.TestBaseService; import com.webank.weid.protocol.base.Credential; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; /** * Testing getCredentialJson method. 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 7a5b71080..0dd9a75ec 100644 --- a/src/test/java/com/webank/weid/full/credential/TestVerifyCredential.java +++ b/src/test/java/com/webank/weid/full/credential/TestVerifyCredential.java @@ -17,7 +17,7 @@ import com.webank.weid.common.LogUtil; import com.webank.weid.common.PasswordKey; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.constant.ParamKeyConstant; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; @@ -26,7 +26,7 @@ import com.webank.weid.protocol.base.CredentialWrapper; import com.webank.weid.protocol.base.WeIdDocument; import com.webank.weid.protocol.request.CreateCredentialArgs; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.service.impl.WeIdServiceImpl; import com.webank.weid.util.DataToolUtils; 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 ae363d5b5..73b3ef6f6 100644 --- a/src/test/java/com/webank/weid/full/credential/TestVerifyCredentialWithSpecifiedPubKey.java +++ b/src/test/java/com/webank/weid/full/credential/TestVerifyCredentialWithSpecifiedPubKey.java @@ -9,13 +9,13 @@ import com.webank.weid.common.LogUtil; import com.webank.weid.common.PasswordKey; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.CredentialWrapper; import com.webank.weid.protocol.base.WeIdPublicKey; import com.webank.weid.protocol.request.CreateCredentialArgs; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; /** * verifyCredentialWithSpecifiedPubKey method for testing CredentialService. diff --git a/src/test/java/com/webank/weid/full/credentialpojo/TestCreateCredentialPojo.java b/src/test/java/com/webank/weid/full/credentialpojo/TestCreateCredentialPojo.java index 2d174c4b3..e84389848 100644 --- a/src/test/java/com/webank/weid/full/credentialpojo/TestCreateCredentialPojo.java +++ b/src/test/java/com/webank/weid/full/credentialpojo/TestCreateCredentialPojo.java @@ -22,7 +22,7 @@ import com.webank.weid.common.PasswordKey; import com.webank.weid.constant.CredentialConstant; import com.webank.weid.constant.CredentialType; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.CptBaseInfo; @@ -35,7 +35,7 @@ import com.webank.weid.protocol.request.CreateCredentialPojoArgs; import com.webank.weid.protocol.request.CreateWeIdArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.util.CredentialPojoUtils; import com.webank.weid.util.DataToolUtils; import com.webank.weid.util.DateUtils; diff --git a/src/test/java/com/webank/weid/full/credentialpojo/TestCreatePresentation.java b/src/test/java/com/webank/weid/full/credentialpojo/TestCreatePresentation.java index 78f4aa1ec..d373dfab5 100644 --- a/src/test/java/com/webank/weid/full/credentialpojo/TestCreatePresentation.java +++ b/src/test/java/com/webank/weid/full/credentialpojo/TestCreatePresentation.java @@ -13,7 +13,7 @@ import org.slf4j.LoggerFactory; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.Challenge; @@ -22,7 +22,7 @@ import com.webank.weid.protocol.base.PresentationE; import com.webank.weid.protocol.base.PresentationPolicyE; import com.webank.weid.protocol.base.WeIdAuthentication; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.util.DataToolUtils; import com.webank.weid.util.DateUtils; diff --git a/src/test/java/com/webank/weid/full/credentialpojo/TestCreateSelectiveCredential.java b/src/test/java/com/webank/weid/full/credentialpojo/TestCreateSelectiveCredential.java index 9e472a06a..7c72e547b 100644 --- a/src/test/java/com/webank/weid/full/credentialpojo/TestCreateSelectiveCredential.java +++ b/src/test/java/com/webank/weid/full/credentialpojo/TestCreateSelectiveCredential.java @@ -14,7 +14,7 @@ import com.webank.weid.common.LogUtil; import com.webank.weid.constant.CredentialConstant; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.ClaimPolicy; @@ -22,7 +22,7 @@ import com.webank.weid.protocol.base.WeIdAuthentication; import com.webank.weid.protocol.request.CreateCredentialPojoArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.util.CredentialPojoUtils; import com.webank.weid.util.DataToolUtils; import com.webank.weid.util.DateUtils; 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 cda596f3a..66c9e8e75 100644 --- a/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialByIssuer.java +++ b/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialByIssuer.java @@ -14,14 +14,14 @@ import com.webank.weid.common.LogUtil; import com.webank.weid.common.PasswordKey; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.constant.ParamKeyConstant; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.CptBaseInfo; import com.webank.weid.protocol.base.CredentialPojo; import com.webank.weid.protocol.base.WeIdDocument; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.service.impl.WeIdServiceImpl; /** 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 84396cecd..8f93a3e16 100644 --- a/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialByPublicKey.java +++ b/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialByPublicKey.java @@ -14,7 +14,7 @@ import com.webank.weid.common.LogUtil; import com.webank.weid.common.PasswordKey; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.constant.ParamKeyConstant; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; @@ -22,7 +22,7 @@ import com.webank.weid.protocol.base.CredentialPojo; import com.webank.weid.protocol.base.WeIdDocument; import com.webank.weid.protocol.base.WeIdPublicKey; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.service.impl.WeIdServiceImpl; /** diff --git a/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialWithPresentation.java b/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialWithPresentation.java index 4314d9201..d06bc501c 100644 --- a/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialWithPresentation.java +++ b/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialWithPresentation.java @@ -1,11 +1,11 @@ package com.webank.weid.full.credentialpojo; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.full.persistence.TestBaseTransportation; import com.webank.weid.protocol.base.*; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; diff --git a/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialWithSpecifiedPubKey.java b/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialWithSpecifiedPubKey.java index 88a46fefd..721279184 100644 --- a/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialWithSpecifiedPubKey.java +++ b/src/test/java/com/webank/weid/full/credentialpojo/TestVerifyCredentialWithSpecifiedPubKey.java @@ -9,13 +9,13 @@ import com.webank.weid.common.LogUtil; import com.webank.weid.common.PasswordKey; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.CredentialWrapper; import com.webank.weid.protocol.base.WeIdPublicKey; import com.webank.weid.protocol.request.CreateCredentialArgs; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; /** * verifyCredentialWithSpecifiedPubKey method for testing CredentialService. 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 f0db8ef2c..7625b5b65 100644 --- a/src/test/java/com/webank/weid/full/evidence/TestCreateEvidence.java +++ b/src/test/java/com/webank/weid/full/evidence/TestCreateEvidence.java @@ -3,7 +3,7 @@ package com.webank.weid.full.evidence; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.protocol.base.Credential; import com.webank.weid.protocol.base.CredentialPojo; @@ -11,10 +11,12 @@ import com.webank.weid.protocol.base.WeIdAuthentication; import com.webank.weid.protocol.request.TransactionArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; +import com.webank.weid.service.local.EvidenceServiceLocal; import com.webank.weid.util.DataToolUtils; import com.webank.weid.util.DateUtils; +import com.webank.weid.util.PropertyUtils; import com.webank.weid.util.WeIdUtils; import org.apache.commons.lang3.StringUtils; import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair; @@ -79,11 +81,11 @@ public void testCreateEvidence_success() { Assert.assertTrue(evidenceInfo.getCredentialHash().equalsIgnoreCase(hash)); String signerWeId = tempCreateWeIdResultWithSetAttr.getWeId(); Assert.assertTrue(evidenceInfo.getSigners().contains(WeIdUtils.convertWeIdToAddress(signerWeId))); - Assert.assertEquals(evidenceInfo.getSignInfo().get(WeIdUtils.convertWeIdToAddress(signerWeId)).getLogs().size(), 2); + Assert.assertEquals(evidenceInfo.getSignInfo().get(WeIdUtils.convertWeIdToAddress(signerWeId)).getLogs().size(), 3); Assert.assertTrue( - evidenceInfo.getSignInfo().get(WeIdUtils.convertWeIdToAddress(signerWeId)).getLogs().get(0).equals("1.23")); + evidenceInfo.getSignInfo().get(WeIdUtils.convertWeIdToAddress(signerWeId)).getLogs().get(1).equals("1.23")); Assert.assertTrue( - evidenceInfo.getSignInfo().get(WeIdUtils.convertWeIdToAddress(signerWeId)).getLogs().get(1).equals("13.15")); + evidenceInfo.getSignInfo().get(WeIdUtils.convertWeIdToAddress(signerWeId)).getLogs().get(2).equals("13.15")); ResponseData resp = evidenceService .verifySigner(credential, evidenceInfo, signerWeId); Assert.assertTrue(resp.getResult()); @@ -189,7 +191,7 @@ public void testCreateEvidence_MultipleSigners() { // Another guy signs CreateWeIdDataResult tempCreateWeIdResultWithSetAttr2 = createWeIdWithSetAttr(); ResponseData createResp2 = evidenceService.addSignatureAndLogByHash( - credential.getHash(), "", tempCreateWeIdResultWithSetAttr2.getUserWeIdPrivateKey()); + credential.getHash(), "empty log", tempCreateWeIdResultWithSetAttr2.getUserWeIdPrivateKey()); ResponseData addResp3 = evidenceService.addLogByHash(hash, "abc", tempCreateWeIdResultWithSetAttr2.getUserWeIdPrivateKey()); ResponseData addResp4 = evidenceService.addLogByHash(hash, "eef", @@ -199,8 +201,8 @@ public void testCreateEvidence_MultipleSigners() { EvidenceInfo evidenceInfo = eviInfo.getResult(); String signer1 = tempCreateWeIdResultWithSetAttr.getWeId(); String signer2 = tempCreateWeIdResultWithSetAttr2.getWeId(); - Assert.assertEquals(evidenceInfo.getSignInfo().get(WeIdUtils.convertWeIdToAddress(signer1)).getLogs().size(), 2); - Assert.assertEquals(evidenceInfo.getSignInfo().get(WeIdUtils.convertWeIdToAddress(signer2)).getLogs().size(), 2); + Assert.assertEquals(evidenceInfo.getSignInfo().get(WeIdUtils.convertWeIdToAddress(signer1)).getLogs().size(), 3); + Assert.assertEquals(evidenceInfo.getSignInfo().get(WeIdUtils.convertWeIdToAddress(signer2)).getLogs().size(), 3); ResponseData resp = evidenceService .verifySigner(credential, evidenceInfo, signer1); Assert.assertTrue(resp.getResult()); @@ -387,7 +389,13 @@ public void testBatchCreate() throws Exception { } //EvidenceServiceEngine engine = EngineFactory.createEvidenceServiceEngine(com.webank.weid.blockchain.service.fisco.BaseService.masterGroupId); - com.webank.weid.blockchain.service.impl.EvidenceServiceImpl evidenceBlockchainService = new com.webank.weid.blockchain.service.impl.EvidenceServiceImpl(); + com.webank.weid.blockchain.rpc.EvidenceService evidenceBlockchainService; + if (PropertyUtils.getProperty("deploy.style").equals("blockchain")) { + evidenceBlockchainService = new com.webank.weid.blockchain.service.impl.EvidenceServiceImpl(); + } else { + // default database + evidenceBlockchainService = new EvidenceServiceLocal(); + } // raw creation Long start = System.currentTimeMillis(); Long end = System.currentTimeMillis(); @@ -407,7 +415,7 @@ public void testBatchCreate() throws Exception { faultyHashValues.addAll(hashValues); faultyHashValues.set(1, null); booleans = evidenceBlockchainService - .batchCreateEvidence(hashValues, signatures, logs, timestamps, signers, privateKey).getResult(); + .batchCreateEvidence(faultyHashValues, signatures, logs, timestamps, signers, privateKey).getResult(); Assert.assertFalse(booleans.get(1)); // custom keys (semi filled) diff --git a/src/test/java/com/webank/weid/full/evidence/TestGetEvidence.java b/src/test/java/com/webank/weid/full/evidence/TestGetEvidence.java index 8133b2b9e..a31325692 100644 --- a/src/test/java/com/webank/weid/full/evidence/TestGetEvidence.java +++ b/src/test/java/com/webank/weid/full/evidence/TestGetEvidence.java @@ -9,11 +9,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.protocol.base.EvidenceInfo; import com.webank.weid.protocol.base.HashString; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.util.DataToolUtils; import com.webank.weid.util.DateUtils; diff --git a/src/test/java/com/webank/weid/full/persistence/TestBaseTransportation.java b/src/test/java/com/webank/weid/full/persistence/TestBaseTransportation.java index f34180734..0d484169e 100644 --- a/src/test/java/com/webank/weid/full/persistence/TestBaseTransportation.java +++ b/src/test/java/com/webank/weid/full/persistence/TestBaseTransportation.java @@ -4,7 +4,7 @@ import java.util.List; import java.util.Map; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.Challenge; @@ -15,7 +15,7 @@ import com.webank.weid.protocol.base.PresentationPolicyE; import com.webank.weid.protocol.base.WeIdAuthentication; import com.webank.weid.protocol.base.WeIdPrivateKey; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; public abstract class TestBaseTransportation extends TestBaseService { diff --git a/src/test/java/com/webank/weid/full/persistence/testmysql/TestMysqlAdd.java b/src/test/java/com/webank/weid/full/persistence/testmysql/TestMysqlAdd.java index 232d60cbd..cb41e4f2b 100644 --- a/src/test/java/com/webank/weid/full/persistence/testmysql/TestMysqlAdd.java +++ b/src/test/java/com/webank/weid/full/persistence/testmysql/TestMysqlAdd.java @@ -3,9 +3,9 @@ package com.webank.weid.full.persistence.testmysql; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.persistence.TestBaseTransportation; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.suite.persistence.Persistence; import com.webank.weid.suite.persistence.PersistenceFactory; import com.webank.weid.suite.persistence.PersistenceType; diff --git a/src/test/java/com/webank/weid/full/persistence/testmysql/TestMysqlDelete.java b/src/test/java/com/webank/weid/full/persistence/testmysql/TestMysqlDelete.java index 9b85b798a..1edcfa86e 100644 --- a/src/test/java/com/webank/weid/full/persistence/testmysql/TestMysqlDelete.java +++ b/src/test/java/com/webank/weid/full/persistence/testmysql/TestMysqlDelete.java @@ -3,9 +3,9 @@ package com.webank.weid.full.persistence.testmysql; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.persistence.TestBaseTransportation; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.suite.persistence.Persistence; import com.webank.weid.suite.persistence.PersistenceFactory; import com.webank.weid.suite.persistence.PersistenceType; diff --git a/src/test/java/com/webank/weid/full/persistence/testmysql/TestMysqlGet.java b/src/test/java/com/webank/weid/full/persistence/testmysql/TestMysqlGet.java index 6978eb538..5f1ef2b2a 100644 --- a/src/test/java/com/webank/weid/full/persistence/testmysql/TestMysqlGet.java +++ b/src/test/java/com/webank/weid/full/persistence/testmysql/TestMysqlGet.java @@ -3,9 +3,9 @@ package com.webank.weid.full.persistence.testmysql; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.persistence.TestBaseTransportation; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.suite.persistence.Persistence; import com.webank.weid.suite.persistence.PersistenceFactory; import com.webank.weid.suite.persistence.PersistenceType; diff --git a/src/test/java/com/webank/weid/full/persistence/testmysql/TestMysqlUpdate.java b/src/test/java/com/webank/weid/full/persistence/testmysql/TestMysqlUpdate.java index d1b72051b..3a8c3d70a 100644 --- a/src/test/java/com/webank/weid/full/persistence/testmysql/TestMysqlUpdate.java +++ b/src/test/java/com/webank/weid/full/persistence/testmysql/TestMysqlUpdate.java @@ -3,9 +3,9 @@ package com.webank.weid.full.persistence.testmysql; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.persistence.TestBaseTransportation; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.suite.persistence.Persistence; import com.webank.weid.suite.persistence.PersistenceFactory; import com.webank.weid.suite.persistence.PersistenceType; diff --git a/src/test/java/com/webank/weid/full/persistence/testredis/TestRedisAdd.java b/src/test/java/com/webank/weid/full/persistence/testredis/TestRedisAdd.java index 8382173a3..43aac8e02 100644 --- a/src/test/java/com/webank/weid/full/persistence/testredis/TestRedisAdd.java +++ b/src/test/java/com/webank/weid/full/persistence/testredis/TestRedisAdd.java @@ -14,8 +14,8 @@ import org.slf4j.LoggerFactory; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.constant.ErrorCode; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.suite.persistence.PersistenceFactory; import com.webank.weid.suite.persistence.Persistence; import com.webank.weid.suite.persistence.PersistenceType; diff --git a/src/test/java/com/webank/weid/full/persistence/testredis/TestRedisDelete.java b/src/test/java/com/webank/weid/full/persistence/testredis/TestRedisDelete.java index 67b0f4076..cdaecc404 100644 --- a/src/test/java/com/webank/weid/full/persistence/testredis/TestRedisDelete.java +++ b/src/test/java/com/webank/weid/full/persistence/testredis/TestRedisDelete.java @@ -9,8 +9,8 @@ import org.slf4j.LoggerFactory; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.constant.ErrorCode; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.suite.persistence.PersistenceFactory; import com.webank.weid.suite.persistence.Persistence; import com.webank.weid.suite.persistence.PersistenceType; diff --git a/src/test/java/com/webank/weid/full/persistence/testredis/TestRedisGet.java b/src/test/java/com/webank/weid/full/persistence/testredis/TestRedisGet.java index afc307baf..0ad4027ad 100644 --- a/src/test/java/com/webank/weid/full/persistence/testredis/TestRedisGet.java +++ b/src/test/java/com/webank/weid/full/persistence/testredis/TestRedisGet.java @@ -3,9 +3,9 @@ package com.webank.weid.full.persistence.testredis; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.persistence.TestBaseTransportation; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.suite.persistence.Persistence; import com.webank.weid.suite.persistence.PersistenceFactory; import com.webank.weid.suite.persistence.PersistenceType; diff --git a/src/test/java/com/webank/weid/full/persistence/testredis/TestRedisUpdate.java b/src/test/java/com/webank/weid/full/persistence/testredis/TestRedisUpdate.java index a6cb223c9..6c3c0678a 100644 --- a/src/test/java/com/webank/weid/full/persistence/testredis/TestRedisUpdate.java +++ b/src/test/java/com/webank/weid/full/persistence/testredis/TestRedisUpdate.java @@ -3,9 +3,9 @@ package com.webank.weid.full.persistence.testredis; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.persistence.TestBaseTransportation; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.suite.persistence.Persistence; import com.webank.weid.suite.persistence.PersistenceFactory; import com.webank.weid.suite.persistence.PersistenceType; 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 8c960838c..a58824fd2 100644 --- a/src/test/java/com/webank/weid/full/weid/TestCreateWeId1.java +++ b/src/test/java/com/webank/weid/full/weid/TestCreateWeId1.java @@ -18,7 +18,7 @@ import com.webank.weid.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; /** * non parametric createWeId method for testing WeIdService. diff --git a/src/test/java/com/webank/weid/full/weid/TestCreateWeId2.java b/src/test/java/com/webank/weid/full/weid/TestCreateWeId2.java index eb5036a68..8e68ff966 100644 --- a/src/test/java/com/webank/weid/full/weid/TestCreateWeId2.java +++ b/src/test/java/com/webank/weid/full/weid/TestCreateWeId2.java @@ -9,7 +9,7 @@ import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.WeIdPrivateKey; import com.webank.weid.protocol.request.CreateWeIdArgs; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import org.apache.commons.lang3.StringUtils; import org.junit.Assert; import org.junit.Test; diff --git a/src/test/java/com/webank/weid/full/weid/TestGetWeIdDocument.java b/src/test/java/com/webank/weid/full/weid/TestGetWeIdDocument.java index a8b4b19e6..a3beeef29 100644 --- a/src/test/java/com/webank/weid/full/weid/TestGetWeIdDocument.java +++ b/src/test/java/com/webank/weid/full/weid/TestGetWeIdDocument.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.webank.weid.common.LogUtil; import com.webank.weid.common.PasswordKey; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.WeIdDocument; @@ -13,7 +13,7 @@ import com.webank.weid.protocol.request.AuthenticationArgs; import com.webank.weid.protocol.request.ServiceArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.protocol.response.WeIdListResult; import org.junit.Assert; import org.junit.Test; diff --git a/src/test/java/com/webank/weid/full/weid/TestGetWeIdDocumentJson.java b/src/test/java/com/webank/weid/full/weid/TestGetWeIdDocumentJson.java index 8c27ae91d..1ff700df4 100644 --- a/src/test/java/com/webank/weid/full/weid/TestGetWeIdDocumentJson.java +++ b/src/test/java/com/webank/weid/full/weid/TestGetWeIdDocumentJson.java @@ -16,12 +16,12 @@ import org.slf4j.LoggerFactory; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.WeIdDocument; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; /** * getWeIdDocumentJson method for testing WeIdService. diff --git a/src/test/java/com/webank/weid/full/weid/TestIsWeIdExist.java b/src/test/java/com/webank/weid/full/weid/TestIsWeIdExist.java index 04d2262f2..1a899e8ec 100644 --- a/src/test/java/com/webank/weid/full/weid/TestIsWeIdExist.java +++ b/src/test/java/com/webank/weid/full/weid/TestIsWeIdExist.java @@ -8,9 +8,9 @@ import org.slf4j.LoggerFactory; import com.webank.weid.common.LogUtil; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; /** * isWeIdExist method for testing WeIdService. diff --git a/src/test/java/com/webank/weid/full/weid/TestSetAuthentication.java b/src/test/java/com/webank/weid/full/weid/TestSetAuthentication.java index df59d8c76..779c06941 100644 --- a/src/test/java/com/webank/weid/full/weid/TestSetAuthentication.java +++ b/src/test/java/com/webank/weid/full/weid/TestSetAuthentication.java @@ -9,14 +9,14 @@ import com.webank.weid.common.LogUtil; import com.webank.weid.common.PasswordKey; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.WeIdDocument; import com.webank.weid.protocol.base.WeIdPrivateKey; import com.webank.weid.protocol.request.AuthenticationArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; import com.webank.weid.util.DateUtils; /** diff --git a/src/test/java/com/webank/weid/full/weid/TestSetService.java b/src/test/java/com/webank/weid/full/weid/TestSetService.java index 669912157..98efa6bdc 100644 --- a/src/test/java/com/webank/weid/full/weid/TestSetService.java +++ b/src/test/java/com/webank/weid/full/weid/TestSetService.java @@ -9,13 +9,13 @@ import com.webank.weid.common.LogUtil; import com.webank.weid.common.PasswordKey; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.full.TestBaseService; import com.webank.weid.full.TestBaseUtil; import com.webank.weid.protocol.base.WeIdDocument; import com.webank.weid.protocol.base.WeIdPrivateKey; import com.webank.weid.protocol.request.ServiceArgs; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; /** * setService method for testing WeIdService. diff --git a/src/test/java/com/webank/weid/performance/TestWeIdPerformance.java b/src/test/java/com/webank/weid/performance/TestWeIdPerformance.java index add863e6d..771f88ef8 100644 --- a/src/test/java/com/webank/weid/performance/TestWeIdPerformance.java +++ b/src/test/java/com/webank/weid/performance/TestWeIdPerformance.java @@ -10,11 +10,11 @@ import org.slf4j.LoggerFactory; import com.webank.weid.BaseTest; -import com.webank.weid.constant.ErrorCode; +import com.webank.weid.blockchain.constant.ErrorCode; import com.webank.weid.protocol.base.WeIdDocument; import com.webank.weid.protocol.request.ServiceArgs; import com.webank.weid.protocol.response.CreateWeIdDataResult; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.protocol.response.ResponseData; /** * performance testing. diff --git a/src/test/java/com/webank/weid/util/TestBeanUtil.java b/src/test/java/com/webank/weid/util/TestBeanUtil.java index 1ef5ef4de..d6e8077a5 100644 --- a/src/test/java/com/webank/weid/util/TestBeanUtil.java +++ b/src/test/java/com/webank/weid/util/TestBeanUtil.java @@ -17,8 +17,8 @@ import com.webank.weid.common.BeanUtil; import com.webank.weid.common.PasswordKey; -import com.webank.weid.constant.ErrorCode; -import com.webank.weid.protocol.response.ResponseData; +import com.webank.weid.blockchain.constant.ErrorCode; +import com.webank.weid.blockchain.protocol.response.ResponseData; /** * test for BeanUtil. diff --git a/src/test/resources/fisco.properties.tpl b/src/test/resources/fisco.properties.tpl index 734eca809..d04612282 100644 --- a/src/test/resources/fisco.properties.tpl +++ b/src/test/resources/fisco.properties.tpl @@ -57,9 +57,9 @@ group.id=1 sdk.sm-crypto=false # fisco-bcos sdk cert path contains[ca.crt,sdk.crt,sdk.key] # if sdk.sm-crypto is true, contains [gm] directory, and gm dir contains [gmca.crt,gmsdk.crt,gmsdk.key,gmensdk.crt,gmensdk.key] -sdk.cert-path=conf +sdk.cert-path=resources/conf # amop public key of pem and private key of p12 configuration -amop.pub-path=conf/amop/consumer_public_key.pem -amop.pri-path=conf/amop/consumer_private_key.p12 +amop.pub-path=resources/conf/amop/consumer_public_key.pem +amop.pri-path=resources/conf/amop/consumer_private_key.p12 amop.p12-password=123456 \ No newline at end of file diff --git a/src/test/resources/weidentity.properties.tpl b/src/test/resources/weidentity.properties.tpl index 3b80d1889..57b3571ee 100644 --- a/src/test/resources/weidentity.properties.tpl +++ b/src/test/resources/weidentity.properties.tpl @@ -3,9 +3,20 @@ # application config # # # ####################################################################################################### +# Deploy WeIdentity with blockchain or only database +deploy.style=${DEPLOY_STYLE} +# Crypto type, only use for deploy with database, 0 for ECDSA, 1 for SM +crypto.type=${CRYPTO_TYPE} + # The organization ID for AMOP communication. blockchain.orgid=${ORG_ID} +# The Blockchain Type +blockchain.type=${CHAIN_TYPE} + +# The Chain Id +chain.id=${CHAIN_ID} + # AMOP Config # Timeout for amop request, default: 5000ms amop.request.timeout=5000 @@ -96,6 +107,16 @@ domain.weIdAuth=datasource1:weid_auth domain.resourceInfo=datasource1:resource_info domain.resourceInfo.timeout=31556908799941 +# tables for running locally +local.weIdDocument=datasource1:table_weid_document +local.cpt=datasource1:table_cpt +local.policy=datasource1:table_policy +local.presentation=datasource1:table_presentation +local.role=datasource1:table_role +local.authorityIssuer=datasource1:table_authority_issuer +local.specificIssuer=datasource1:table_specific_issuer +local.evidence=datasource1:table_evidence + ####################################################################################################### # #