├── .gitignore ├── PostmanConfig ├── invoke.postman_collection.json └── weidentity-restservice.postman_environment.json ├── README.md ├── build.gradle ├── dependencies ├── .gitkeep └── wallet-agent-0.1.0.jar ├── fisco.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── keys └── priv │ └── .gitkeep ├── private_key ├── script ├── deploy_payment.sh ├── server_status.sh ├── start.sh └── stop.sh ├── settings.gradle ├── src ├── main │ ├── java │ │ └── com │ │ │ └── webank │ │ │ └── weid │ │ │ └── http │ │ │ ├── Application.java │ │ │ ├── aspect │ │ │ └── ServiceLogAspect.java │ │ │ ├── config │ │ │ ├── BeanConfig.java │ │ │ └── HttpsConfig.java │ │ │ ├── constant │ │ │ ├── HttpReturnCode.java │ │ │ ├── SignType.java │ │ │ ├── WalletAgentFunctionNames.java │ │ │ ├── WeIdentityFunctionNames.java │ │ │ ├── WeIdentityParamKeyConstant.java │ │ │ └── WeIdentityServiceEndpoint.java │ │ │ ├── controller │ │ │ └── TransactionController.java │ │ │ ├── protocol │ │ │ ├── base │ │ │ │ ├── ResolutionMetadata.java │ │ │ │ ├── ResolveData.java │ │ │ │ └── ResolveDataJsonLD.java │ │ │ ├── request │ │ │ │ ├── EndpointRequest.java │ │ │ │ ├── InputArg.java │ │ │ │ ├── ReqInput.java │ │ │ │ ├── TransactionArg.java │ │ │ │ └── payment │ │ │ │ │ ├── AssetAddressList.java │ │ │ │ │ ├── BAC004BatchSendInfo.java │ │ │ │ │ ├── BAC004Info.java │ │ │ │ │ ├── BAC004SendInfo.java │ │ │ │ │ ├── BAC005BatchInfo.java │ │ │ │ │ ├── BAC005Info.java │ │ │ │ │ ├── BaseQuery.java │ │ │ │ │ └── PageQuery.java │ │ │ └── response │ │ │ │ ├── EncodedTransactionWrapper.java │ │ │ │ ├── EndpointInfo.java │ │ │ │ ├── HttpResponseData.java │ │ │ │ └── WeIdListRsp.java │ │ │ ├── service │ │ │ ├── AuthService.java │ │ │ ├── BaseService.java │ │ │ ├── EndpointService.java │ │ │ ├── InvokeService.java │ │ │ ├── InvokerAuthorityIssuerService.java │ │ │ ├── InvokerCptService.java │ │ │ ├── InvokerCredentialService.java │ │ │ ├── InvokerEvidenceService.java │ │ │ ├── InvokerWeIdService.java │ │ │ ├── RawTransaction.java │ │ │ ├── TransactionService.java │ │ │ ├── impl │ │ │ │ ├── AuthServiceImpl.java │ │ │ │ ├── EndpointServiceImpl.java │ │ │ │ ├── InvokerAuthorityIssuerServiceImpl.java │ │ │ │ ├── InvokerCptServiceImpl.java │ │ │ │ ├── InvokerCredentialServiceImpl.java │ │ │ │ ├── InvokerEvidenceServiceImpl.java │ │ │ │ ├── InvokerWeIdServiceImpl.java │ │ │ │ └── TransactionServiceImpl.java │ │ │ └── rpc │ │ │ │ ├── FixedLengthProtocol.java │ │ │ │ ├── RpcClient.java │ │ │ │ ├── RpcConnectionHandler.java │ │ │ │ └── SendTester.java │ │ │ └── util │ │ │ ├── EndpointDataUtil.java │ │ │ ├── JsonUtil.java │ │ │ ├── KeyUtil.java │ │ │ ├── PropertiesUtil.java │ │ │ ├── TransactionEncoderUtil.java │ │ │ └── TransactionEncoderUtilV2.java │ └── resources │ │ ├── SpringApplicationContext.xml │ │ ├── WeDPR_dynamic_lib │ │ ├── ffi_selective_disclosure.dll │ │ ├── libeay32md.dll │ │ ├── libffi_selective_disclosure.so │ │ └── ssleay32md.dll │ │ ├── amop │ │ ├── consumer_private_key.p12 │ │ └── consumer_public_key.pem │ │ ├── application.properties │ │ ├── client.keystore │ │ ├── cpt.json │ │ ├── endpoint-data.properties │ │ ├── fisco.properties │ │ ├── log4j2.xml │ │ ├── server.keystore │ │ ├── tb.jks │ │ └── weidentity.properties └── test │ ├── java │ └── com │ │ └── webank │ │ └── weid │ │ └── http │ │ ├── BaseTest.java │ │ └── service │ │ ├── CredentialTest.java │ │ ├── EnCodeAndTranscatTest.java │ │ ├── PrivateKeyTest.java │ │ ├── PropertiesTest.java │ │ ├── PureInvokerTest.java │ │ ├── TransactionTest.java │ │ └── TransactionTestV2.java │ └── resources │ ├── SpringApplicationContext.xml │ ├── client.keystore │ ├── cpt.json │ ├── log4j2.xml │ ├── server.keystore │ └── tb.jks └── weidentity.properties /.gitignore: -------------------------------------------------------------------------------- 1 | Created by https://www.gitignore.io/api/vim,java,maven,gradle,java-web,intellij,intellij+iml 2 | 3 | ### Intellij ### 4 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 5 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 6 | 7 | # User-specific stuff: 8 | .idea/**/workspace.xml 9 | .idea/**/tasks.xml 10 | .idea/dictionaries 11 | .idea/checkstyle-idea.xml 12 | 13 | # Sensitive or high-churn files: 14 | .idea/**/dataSources/ 15 | .idea/**/dataSources.ids 16 | .idea/**/dataSources.xml 17 | .idea/**/dataSources.local.xml 18 | .idea/**/sqlDataSources.xml 19 | .idea/**/dynamic.xml 20 | .idea/**/uiDesigner.xml 21 | 22 | # Gradle: 23 | .idea/**/gradle.xml 24 | .idea/**/libraries 25 | 26 | # CMake 27 | cmake-build-debug/ 28 | 29 | # Mongo Explorer plugin: 30 | .idea/**/mongoSettings.xml 31 | 32 | # For idea 33 | .idea 34 | 35 | ## File-based project format: 36 | *.iws 37 | 38 | ## Plugin-specific files: 39 | 40 | # IntelliJ 41 | /out/ 42 | 43 | # mpeltonen/sbt-idea plugin 44 | .idea_modules/ 45 | 46 | # JIRA plugin 47 | atlassian-ide-plugin.xml 48 | 49 | # Cursive Clojure plugin 50 | .idea/replstate.xml 51 | 52 | # Crashlytics plugin (for Android Studio and IntelliJ) 53 | com_crashlytics_export_strings.xml 54 | crashlytics.properties 55 | crashlytics-build.properties 56 | fabric.properties 57 | 58 | ### Intellij Patch ### 59 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 60 | 61 | # *.iml 62 | # modules.xml 63 | # .idea/misc.xml 64 | # *.ipr 65 | 66 | # Sonarlint plugin 67 | .idea/sonarlint 68 | 69 | ### Intellij+iml ### 70 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 71 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 72 | 73 | # User-specific stuff: 74 | 75 | # Sensitive or high-churn files: 76 | 77 | # Gradle: 78 | 79 | # CMake 80 | 81 | # Mongo Explorer plugin: 82 | 83 | ## File-based project format: 84 | 85 | ## Plugin-specific files: 86 | 87 | # IntelliJ 88 | 89 | # mpeltonen/sbt-idea plugin 90 | 91 | # JIRA plugin 92 | 93 | # Cursive Clojure plugin 94 | 95 | # Crashlytics plugin (for Android Studio and IntelliJ) 96 | 97 | ### Intellij+iml Patch ### 98 | # Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023 99 | 100 | *.iml 101 | modules.xml 102 | .idea/misc.xml 103 | *.ipr 104 | 105 | ### Java ### 106 | # Compiled class file 107 | *.class 108 | 109 | # Log file 110 | *.log 111 | 112 | # BlueJ files 113 | *.ctxt 114 | 115 | # Mobile Tools for Java (J2ME) 116 | .mtj.tmp/ 117 | 118 | # Package Files # 119 | *.jar 120 | *.war 121 | *.ear 122 | *.zip 123 | *.tar.gz 124 | *.rar 125 | 126 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 127 | hs_err_pid* 128 | 129 | ### Java-Web ### 130 | ## ignoring target file 131 | target/ 132 | 133 | ### Maven ### 134 | pom.xml.tag 135 | pom.xml.releaseBackup 136 | pom.xml.versionsBackup 137 | pom.xml.next 138 | release.properties 139 | dependency-reduced-pom.xml 140 | buildNumber.properties 141 | .mvn/timing.properties 142 | 143 | # Avoid ignoring Maven wrapper jar file (.jar files are usually ignored) 144 | !/.mvn/wrapper/maven-wrapper.jar 145 | 146 | ### Vim ### 147 | # swap 148 | [._]*.s[a-v][a-z] 149 | [._]*.sw[a-p] 150 | [._]s[a-v][a-z] 151 | [._]sw[a-p] 152 | # session 153 | Session.vim 154 | # temporary 155 | .netrwhist 156 | *~ 157 | # auto-generated tag files 158 | tags 159 | 160 | ### Gradle ### 161 | .gradle 162 | /build/ 163 | 164 | # Ignore Gradle GUI config 165 | gradle-app.setting 166 | 167 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 168 | !gradle-wrapper.jar 169 | 170 | # Cache of project 171 | .gradletasknamecache 172 | 173 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 174 | # gradle/wrapper/gradle-wrapper.properties 175 | 176 | # End of https://www.gitignore.io/api/vim,java,maven,gradle,java-web,intellij,intellij+iml 177 | 178 | # added by junqizhang 179 | build.tar.gz 180 | .rsync.sh 181 | rsync.ex 182 | build/ 183 | dist/ 184 | bak/ 185 | *docx 186 | *pdf 187 | *jpg 188 | javadoc/ 189 | 190 | # for specific project 191 | doc/bak/ 192 | /bin/ 193 | 194 | # for eclipse 195 | .settings/ 196 | .project 197 | .classpath 198 | keys/ 199 | /resources/ 200 | logs/ -------------------------------------------------------------------------------- /PostmanConfig/weidentity-restservice.postman_environment.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "e9e5df8a-f86d-4fd3-8c04-370dce21bb2d", 3 | "name": "weidentity-restservice", 4 | "values": [ 5 | { 6 | "key": "host", 7 | "value": "127.0.0.1", 8 | "description": "", 9 | "enabled": true 10 | }, 11 | { 12 | "key": "httpport", 13 | "value": "6001", 14 | "description": "", 15 | "enabled": true 16 | } 17 | ], 18 | "_postman_variable_scope": "environment", 19 | "_postman_exported_at": "2019-04-02T11:00:27.074Z", 20 | "_postman_exported_using": "Postman/7.0.6" 21 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WeIdentity HTTP Service 2 | 3 | --- 4 | 5 | ## 总体介绍 6 | WeIdentity Restful HTTP Service提供了简化的WeIdentity集成方式与访问能力。 7 | 使用者仅需部署一台Java的机器, 8 | 便可以使用各种类型的HTTP/HTTPS协议访问WeIdentity的功能了, 9 | 不再需要通过Java API方式调用SDK。 10 | 11 | ## 功能介绍 12 | 目前,WeIdentity RestService支持客户端密钥管理、服务器端密钥托管、数字身份标识(WeIdentity DID)管理、 13 | 标准化凭证(WeIdentity Credential)管理、授权机构(Authority Issuer)管理、标准化模板(CPT)管理等功能。 14 | 15 | 详细的设计及使用说明,请参见 [WeIdentity RestService文档](https://weidentity.readthedocs.io/zh_CN/latest/docs/weidentity-rest.html) 16 | 17 | WeIdentity及其组件的[兼容版本说明文档](https://weidentity.readthedocs.io/zh_CN/develop/docs/compatibility.html) 请查看! 18 | 19 | ## 联系我们 20 | 21 | 邮箱:weidentity@webank.com 22 | 23 | ## License 24 | 25 | This project is released under [Apache-2.0](http://www.apache.org/licenses/LICENSE-2.0). 26 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | def gradleVer = "4" 2 | if (gradle.gradleVersion.startsWith("6") 3 | || gradle.gradleVersion.startsWith("5") 4 | || gradle.gradleVersion.startsWith("4.10") 5 | || gradle.gradleVersion.startsWith("4.9") 6 | || gradle.gradleVersion.startsWith("4.8") 7 | || gradle.gradleVersion.startsWith("4.7")) { 8 | println "Gradle with version >= 4.7 detected" 9 | gradleVer = "5" 10 | } else { 11 | println "Gradle with version < 4.7 detected" 12 | } 13 | 14 | apply plugin: 'maven' 15 | apply plugin: 'java' 16 | apply plugin: 'eclipse' 17 | apply plugin: 'idea' 18 | 19 | version = "1.7.0" 20 | 21 | // Specify JDK version - may vary in different scenarios 22 | sourceCompatibility = 1.8 23 | targetCompatibility = 1.8 24 | 25 | [compileJava, compileTestJava, javadoc]*.options*.encoding = 'UTF-8' 26 | // In this section you declare where to find the dependencies of your project 27 | repositories { 28 | maven { 29 | url "http://maven.aliyun.com/nexus/content/groups/public/" 30 | mavenCentral() 31 | } 32 | //maven { url "https://dl.bintray.com/ethereum/maven/" } 33 | maven { url "https://oss.sonatype.org/content/repositories/snapshots" } 34 | maven { url "https://oss.sonatype.org/content/groups/public/" } 35 | mavenLocal() 36 | } 37 | 38 | List lombok = [ 39 | 'org.projectlombok:lombok:1.18.12' 40 | ] 41 | 42 | def spring_version = "5.3.18" 43 | List spring = [ 44 | "org.springframework:spring-core:$spring_version", 45 | "org.springframework:spring-beans:$spring_version", 46 | "org.springframework:spring-context:$spring_version", 47 | "org.springframework:spring-tx:$spring_version", 48 | "org.springframework:spring-jdbc:$spring_version", 49 | "org.springframework:spring-test:$spring_version", 50 | "org.springframework:spring-context-support:$spring_version", 51 | "org.springframework:spring-web:$spring_version", 52 | "org.springframework:spring-webmvc:$spring_version" 53 | ] 54 | 55 | def spring_boot_version = "2.4.1" 56 | List spring_boot = [ 57 | "org.springframework.boot:spring-boot-starter-web:$spring_boot_version", 58 | "org.springframework.boot:spring-boot-autoconfigure:$spring_boot_version", 59 | "org.springframework.boot:spring-boot-configuration-processor:$spring_boot_version", 60 | "org.springframework.boot:spring-boot-starter-log4j2:$spring_boot_version", 61 | "org.springframework.boot:spring-boot-starter-aop:$spring_boot_version" 62 | ] 63 | 64 | def log4j_version = "2.18.0" 65 | List log4j = [ 66 | "org.apache.logging.log4j:log4j-api:$log4j_version", 67 | "org.apache.logging.log4j:log4j-web:$log4j_version", 68 | "org.apache.logging.log4j:log4j-core:$log4j_version", 69 | "org.apache.logging.log4j:log4j-jcl:$log4j_version", 70 | "org.apache.logging.log4j:log4j-jul:$log4j_version", 71 | "org.apache.logging.log4j:log4j-slf4j-impl:$log4j_version" 72 | ] 73 | 74 | List spring_boot_test = [ 75 | "org.springframework.boot:spring-boot-starter-test:$spring_boot_version" 76 | ] 77 | 78 | // junit test 79 | List junit = [ 80 | "junit:junit:4.13.1", 81 | "org.springframework:spring-test:$spring_version" 82 | ] 83 | 84 | // In this section you declare the dependencies for your production and test code 85 | List json = [ 86 | "javax.validation:validation-api:1.1.0.Final", 87 | "com.google.code.gson:gson:2.8.9" 88 | ] 89 | 90 | List weid = [ 91 | 'com.webank:weid-java-sdk:3.1.1-rc.2-SNAPSHOT', 92 | "com.webank:weid-kit:3.1.0-rc.1" 93 | ] 94 | 95 | // In this section you declare the dependencies for your production and test code 96 | dependencies { 97 | compile spring, json, spring_boot, log4j 98 | testCompile spring, json, junit, spring_boot, log4j, spring_boot_test 99 | // Check SDK pipeline dependency 100 | if (file("./dependencies/weid-java-sdk-pipeline.jar").exists()) { 101 | println "Pipeline jar for WeIdentity Java SDK found." 102 | compile files('./dependencies/weid-java-sdk-pipeline.jar') 103 | testCompile files('./dependencies/weid-java-sdk-pipeline.jar') 104 | compile fileTree(dir: 'libs', include: '*.jar') 105 | testCompile fileTree(dir: 'libs', include: '*.jar') 106 | } else { 107 | println "No pipeline jar found for WeIdentity Java SDK, using gradle version.." 108 | compile weid 109 | testCompile weid 110 | } 111 | if (gradleVer.startsWith("4")) { 112 | compile lombok 113 | testCompile lombok 114 | } 115 | if (gradleVer.startsWith("5")) { 116 | compileOnly lombok 117 | annotationProcessor lombok 118 | testAnnotationProcessor lombok 119 | testCompileOnly lombok 120 | } 121 | compile files('./dependencies/wallet-agent-0.1.0.jar') 122 | } 123 | 124 | configurations { 125 | all*.exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging' 126 | all*.exclude group: "io.netty", module: "netty-tcnative" 127 | } 128 | 129 | sourceSets { 130 | main { 131 | java { 132 | srcDirs = ['src/main/java'] 133 | } 134 | resources { 135 | srcDirs = ['src/main/resources'] 136 | } 137 | } 138 | test { 139 | java { 140 | srcDirs = ['src/test/java'] 141 | } 142 | resources { 143 | srcDirs = ['src/test/resources'] 144 | } 145 | } 146 | } 147 | 148 | eclipse { 149 | classpath { 150 | downloadSources = false 151 | } 152 | } 153 | 154 | jar { 155 | destinationDir file('dist/apps') 156 | archiveName project.name + '-' + version + '.jar' 157 | exclude '**/*.xml', '**/*.properties' 158 | 159 | doLast { 160 | copy { 161 | from file('src/main/resources/') 162 | into 'dist/conf' 163 | } 164 | copy { 165 | from file('script/') 166 | into 'dist' 167 | } 168 | copy { 169 | from configurations.runtime 170 | into 'dist/lib' 171 | } 172 | copy { 173 | from file('keys/priv') 174 | into 'dist/keys/priv' 175 | } 176 | copy { 177 | from file('private_key') 178 | into 'dist' 179 | } 180 | copy { 181 | from file('.').listFiles().findAll { File f -> (f.name.endsWith('.bat') || f.name.endsWith('.sh') || f.name.endsWith('.env')) } 182 | into 'dist' 183 | } 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /dependencies/.gitkeep: -------------------------------------------------------------------------------- 1 | # Ignore everything in this directory 2 | * 3 | # Except this file !.gitkeep -------------------------------------------------------------------------------- /dependencies/wallet-agent-0.1.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WeBankBlockchain/WeIdentity-Rest-Service/437042e6a4d3a56e52bb1a45fd52bf54fc870ce9/dependencies/wallet-agent-0.1.0.jar -------------------------------------------------------------------------------- /fisco.properties: -------------------------------------------------------------------------------- 1 | # Fisco-bcos blockchain node related properties 2 | 3 | ####################################################################################################### 4 | # # 5 | # fisco bcos version config # 6 | # # 7 | ####################################################################################################### 8 | # Version 9 | bcos.version=2 10 | 11 | 12 | ####################################################################################################### 13 | # # 14 | # contract address config # 15 | # # 16 | ####################################################################################################### 17 | # contract address 18 | weId.contractaddress= 19 | cpt.contractaddress= 20 | issuer.contractaddress= 21 | evidence.contractaddress= 22 | specificissuer.contractaddress= 23 | 24 | # This variable is used to distinguish the environment. You can use "dev" to set the development environment, 25 | # "stg" to set the test environment, "prd" to set the production environment, 26 | # If you do not set it, the system will use allOrg as the environment by default. 27 | # It is not recommended. Production use default configuration 28 | cns.profile.active=prdabce 29 | 30 | ####################################################################################################### 31 | # # 32 | # web3sdk connection config # 33 | # # 34 | ####################################################################################################### 35 | # blockchain connection params 36 | web3sdk.timeout=30 37 | web3sdk.core-pool-size=100 38 | web3sdk.max-pool-size=200 39 | web3sdk.queue-capacity=1000 40 | web3sdk.keep-alive-seconds=60 41 | 42 | 43 | ####################################################################################################### 44 | # # 45 | # fisco bcos 2.0 related config # 46 | # # 47 | ####################################################################################################### 48 | # Fisco-Bcos 2.x params, including Group ID and Encrypt Type 49 | group.id=1 50 | 51 | ####################################################################################################### 52 | # # 53 | # fisco bcos node cert related config # 54 | # # 55 | ####################################################################################################### 56 | # Fisco-Bcos sdk SSL encrypt type, 0:ECDSA, 1:SM2 57 | sdk.sm-crypto=0 58 | # fisco-bcos sdk cert path contains[ca.crt,sdk.crt,sdk.key] 59 | # if sdk.sm-crypto is true, contains [gm] directory, and gm dir contains [gmca.crt,gmsdk.crt,gmsdk.key,gmensdk.crt,gmensdk.key] 60 | sdk.cert-path=resources/conf 61 | 62 | # amop public key of pem and private key of p12 configuration 63 | amop.pub-path=resources/conf/amop/consumer_public_key.pem 64 | amop.pri-path=resources/conf/amop/consumer_private_key.p12 65 | amop.p12-password=123456 -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WeBankBlockchain/WeIdentity-Rest-Service/437042e6a4d3a56e52bb1a45fd52bf54fc870ce9/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.8-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /keys/priv/.gitkeep: -------------------------------------------------------------------------------- 1 | # Ignore everything in this directory 2 | * 3 | # Except this file !.gitkeep -------------------------------------------------------------------------------- /private_key: -------------------------------------------------------------------------------- 1 | 49191370627614877492996337821917274297863513005433547861103892894089436256261 -------------------------------------------------------------------------------- /script/deploy_payment.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | JAVA_HOME="$JAVA_HOME" 4 | 5 | if [ -f conf/payment.properties ];then 6 | echo "Err: the conf/payment.properties is exists" 7 | exit 1 8 | fi 9 | 10 | key=$(cat keys/priv/private_key) 11 | 12 | ${JAVA_HOME}/bin/java -classpath "./conf:./lib/*" com.webank.payment.contract.deploy.DeployService ${key} 13 | if [[ $? -ne 0 ]];then 14 | echo "deploy contract failed." 15 | exit 1 16 | fi 17 | 18 | if [ -f payment.properties ];then 19 | cp payment.properties ./conf/ 20 | rm payment.properties 21 | rm private_key 22 | fi 23 | -------------------------------------------------------------------------------- /script/server_status.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # get JAVA_HOME conf from server.env 4 | #TEMP_JAVA_HOME=`cat server.env | grep JAVA_HOME | cut -d':' -f4` 5 | # jdk path 6 | JAVA_HOME="$JAVA_HOME" 7 | 8 | # Java main 9 | APP_MAIN=com.webank.weid.http.Application 10 | 11 | tradePortalPID=0 12 | 13 | getTradeProtalPID(){ 14 | javaps=`$JAVA_HOME/bin/jps -l | grep $APP_MAIN` 15 | if [ -n "$javaps" ]; then 16 | tradePortalPID=`echo $javaps | awk '{print $1}'` 17 | else 18 | tradePortalPID=0 19 | fi 20 | } 21 | 22 | getServerStatus(){ 23 | getTradeProtalPID 24 | echo "===============================================================================================" 25 | if [ $tradePortalPID -ne 0 ]; then 26 | echo "$APP_MAIN is running(PID=$tradePortalPID)" 27 | echo "===============================================================================================" 28 | else 29 | echo "$APP_MAIN is not running" 30 | echo "===============================================================================================" 31 | fi 32 | } 33 | 34 | getServerStatus -------------------------------------------------------------------------------- /script/start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # get JAVA_HOME conf from server.env 4 | #TEMP_JAVA_HOME=`cat server.env | grep JAVA_HOME | cut -d':' -f4` 5 | # jdk path 6 | JAVA_HOME="$JAVA_HOME" 7 | 8 | CURRENT_DIR=`pwd` 9 | APP_NAME=`basename ${CURRENT_DIR}` 10 | 11 | CONF_DIR=./app/${APP_NAME}/conf 12 | LOG_DIR=./logs/${APP_NAME} 13 | 14 | # Java main 15 | APP_MAIN=com.webank.weid.http.Application 16 | CLASSPATH='conf/:apps/*:lib/*' 17 | 18 | tradePortalPID=0 19 | 20 | getTradeProtalPID(){ 21 | javaps=`$JAVA_HOME/bin/jps -l | grep $APP_MAIN` 22 | if [ -n "$javaps" ]; then 23 | tradePortalPID=`echo $javaps | awk '{print $1}'` 24 | else 25 | tradePortalPID=0 26 | fi 27 | } 28 | 29 | JAVA_OPTS=" -Dfile.encoding=UTF-8 -Djdk.tls.namedGroups=\"secp256r1,secp256k1\"" 30 | JAVA_OPTS+=" -Dlog4j.configurationfile=${CONF_DIR}/log4j2.xml -Dindex.log.home=${LOG_DIR} -Dconfig=${CONF_DIR}/" 31 | JAVA_OPTS+=" -server -Xmx1024m -Xms1024m -XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=128m -XX:MaxPermSize=128m" 32 | JAVA_OPTS+=" -XX:+UseConcMarkSweepGC -XX:+UseCMSCompactAtFullCollection -XX:CMSInitiatingOccupancyFraction=70" 33 | JAVA_OPTS+=" -XX:+CMSParallelRemarkEnabled -XX:SoftRefLRUPolicyMSPerMB=0 -XX:+CMSClassUnloadingEnabled -XX:+DisableExplicitGC -XX:SurvivorRatio=8" 34 | JAVA_OPTS+=" -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${LOG_DIR}/ -XX:ErrorFile=${LOG_DIR}/heap_error.log" 35 | 36 | startup(){ 37 | getTradeProtalPID 38 | echo "===============================================================================================" 39 | if [ $tradePortalPID -ne 0 ]; then 40 | echo "$APP_MAIN already started(PID=$tradePortalPID)" 41 | echo "===============================================================================================" 42 | else 43 | echo -n "Starting $APP_MAIN ..." 44 | nohup $JAVA_HOME/bin/java ${JAVA_OPTS} -cp $CLASSPATH $APP_MAIN >> /dev/null 2>&1 & 45 | getTradeProtalPID 46 | if [ $tradePortalPID -ne 0 ]; then 47 | echo "(PID=$tradePortalPID)...[Success]" 48 | echo "===============================================================================================" 49 | else 50 | echo "[Failed]" 51 | echo "===============================================================================================" 52 | fi 53 | fi 54 | } 55 | 56 | startup -------------------------------------------------------------------------------- /script/stop.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # get JAVA_HOME conf from server.env 4 | #TEMP_JAVA_HOME=`cat server.env | grep JAVA_HOME | cut -d':' -f4` 5 | # jdk path 6 | JAVA_HOME="$JAVA_HOME" 7 | 8 | # Java main 9 | APP_MAIN=com.webank.weid.http.Application 10 | 11 | tradePortalPID=0 12 | 13 | getTradeProtalPID(){ 14 | javaps=`$JAVA_HOME/bin/jps -l | grep $APP_MAIN` 15 | if [ -n "$javaps" ]; then 16 | tradePortalPID=`echo $javaps | awk '{print $1}'` 17 | else 18 | tradePortalPID=0 19 | fi 20 | } 21 | 22 | shutdown(){ 23 | getTradeProtalPID 24 | echo "===============================================================================================" 25 | if [ $tradePortalPID -ne 0 ]; then 26 | echo -n "Stopping $APP_MAIN(PID=$tradePortalPID)..." 27 | kill -9 $tradePortalPID 28 | if [ $? -eq 0 ]; then 29 | echo "[Success]" 30 | echo "===============================================================================================" 31 | else 32 | echo "[Failed]" 33 | echo "===============================================================================================" 34 | fi 35 | getTradeProtalPID 36 | if [ $tradePortalPID -ne 0 ]; then 37 | shutdown 38 | fi 39 | else 40 | echo "$APP_MAIN is not running" 41 | echo "===============================================================================================" 42 | fi 43 | } 44 | 45 | shutdown -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name='weid-http-service' 2 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/Application.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http; 21 | 22 | import com.webank.weid.blockchain.config.FiscoConfig; 23 | import com.webank.weid.util.PropertyUtils; 24 | import org.slf4j.Logger; 25 | import org.slf4j.LoggerFactory; 26 | import org.springframework.boot.SpringApplication; 27 | import org.springframework.boot.autoconfigure.SpringBootApplication; 28 | import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; 29 | import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; 30 | import org.springframework.boot.web.servlet.ServletComponentScan; 31 | import org.springframework.context.annotation.ComponentScan; 32 | 33 | import java.io.InputStream; 34 | import java.net.URL; 35 | 36 | @SpringBootApplication( 37 | exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class} 38 | ) 39 | @ComponentScan("com.webank.weid") 40 | @ServletComponentScan("com.webank.weid") 41 | public class Application { 42 | private static Logger logger = LoggerFactory.getLogger(Application.class); 43 | 44 | public static void main(String[] args) { 45 | SpringApplication.run(Application.class); 46 | FiscoConfig.topic = "weid-http-service"; 47 | logger.info("#### Start finished"); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/aspect/ServiceLogAspect.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.aspect; 21 | 22 | import java.util.Arrays; 23 | 24 | import javax.servlet.http.HttpServletRequest; 25 | 26 | import org.aspectj.lang.JoinPoint; 27 | import org.aspectj.lang.annotation.AfterReturning; 28 | import org.aspectj.lang.annotation.Aspect; 29 | import org.aspectj.lang.annotation.Before; 30 | import org.aspectj.lang.annotation.Pointcut; 31 | import org.slf4j.Logger; 32 | import org.slf4j.LoggerFactory; 33 | import org.springframework.stereotype.Component; 34 | import org.springframework.web.context.request.RequestContextHolder; 35 | import org.springframework.web.context.request.ServletRequestAttributes; 36 | 37 | import com.webank.weid.http.util.JsonUtil; 38 | 39 | @Aspect 40 | @Component 41 | public class ServiceLogAspect { 42 | 43 | private Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class); 44 | 45 | ThreadLocal startTime = new ThreadLocal(); 46 | 47 | @Pointcut("execution(public * com.webank.weid.http.service.*.*(..))") 48 | private void controllerAspect(){ 49 | 50 | } 51 | 52 | /** 53 | * running before joinPoint 54 | * @param joinPoint this is joinPoint 55 | */ 56 | @Before(value = "controllerAspect()") 57 | public void before(JoinPoint joinPoint){ 58 | 59 | startTime.set(System.currentTimeMillis()); 60 | 61 | ServletRequestAttributes requestAttributes = 62 | (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 63 | HttpServletRequest request = requestAttributes.getRequest(); 64 | 65 | logger.info("####request url:{}| type:{}| method:[{}]| args:{}", 66 | request.getRequestURL().toString(), 67 | request.getMethod(), 68 | joinPoint.getSignature(), 69 | Arrays.toString(joinPoint.getArgs())); 70 | } 71 | 72 | /** 73 | * when joinPoint, running after return 74 | * @param joinPoint this is joinPoint 75 | * @param keys return result 76 | */ 77 | @AfterReturning(value = "controllerAspect()", returning = "keys") 78 | public void afterReturning(JoinPoint joinPoint, Object keys) { 79 | 80 | logger.info("####response method:[{}]| args:{}| result:{}| cost tims:{}ms", 81 | joinPoint.getSignature(), 82 | Arrays.asList(joinPoint.getArgs()), 83 | JsonUtil.objToJsonStr(keys), 84 | (System.currentTimeMillis() - startTime.get())); 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/config/BeanConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.config; 21 | 22 | import org.springframework.context.annotation.Bean; 23 | import org.springframework.context.annotation.Configuration; 24 | 25 | import com.webank.weid.service.rpc.AuthorityIssuerService; 26 | import com.webank.weid.service.rpc.CptService; 27 | import com.webank.weid.service.rpc.CredentialService; 28 | import com.webank.weid.service.rpc.WeIdService; 29 | import com.webank.weid.service.impl.AuthorityIssuerServiceImpl; 30 | import com.webank.weid.service.impl.CptServiceImpl; 31 | import com.webank.weid.service.impl.CredentialServiceImpl; 32 | import com.webank.weid.service.impl.WeIdServiceImpl; 33 | 34 | /** 35 | * implement http redirect https. 36 | * 37 | * @author darwindu 38 | */ 39 | @Configuration 40 | public class BeanConfig { 41 | 42 | @Bean("authorityIssuerService") 43 | public AuthorityIssuerService getAuthorityIssuerService() { 44 | return new AuthorityIssuerServiceImpl(); 45 | } 46 | 47 | @Bean("cptService") 48 | public CptService getCptService() { 49 | return new CptServiceImpl(); 50 | } 51 | 52 | @Bean("credentialService") 53 | public CredentialService getCredentialService() { 54 | return new CredentialServiceImpl(); 55 | } 56 | 57 | @Bean("weIdService") 58 | public WeIdService getWeIdService() { 59 | return new WeIdServiceImpl(); 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/config/HttpsConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.config; 21 | 22 | import org.apache.catalina.connector.Connector; 23 | import org.springframework.beans.factory.annotation.Value; 24 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 25 | import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; 26 | import org.springframework.boot.web.servlet.server.ServletWebServerFactory; 27 | import org.springframework.context.annotation.Bean; 28 | import org.springframework.context.annotation.Configuration; 29 | 30 | /** 31 | * implement http redirect https. 32 | * 33 | * @author darwindu/chaoxinhu 34 | */ 35 | @Configuration 36 | @ConditionalOnProperty(value = "server.ssl.enabled", havingValue = "true") 37 | public class HttpsConfig { 38 | 39 | @Value("${server.http.port}") 40 | private Integer serverPort; 41 | 42 | 43 | @Bean 44 | public ServletWebServerFactory servletContainer() { 45 | TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(); 46 | tomcat.addAdditionalTomcatConnectors(createStandardConnector()); 47 | return tomcat; 48 | } 49 | 50 | private Connector createStandardConnector() { 51 | Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); 52 | connector.setPort(serverPort); 53 | return connector; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/constant/HttpReturnCode.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.constant; 21 | 22 | public enum HttpReturnCode { 23 | 24 | /** 25 | * The success. 26 | */ 27 | SUCCESS(0, "success"), 28 | 29 | /** 30 | * base error. 31 | */ 32 | VALUE_FORMAT_ILLEGAL(201000, "Input parameter value format illegal. "), 33 | 34 | /** 35 | * other uncatched exceptions or error. 36 | */ 37 | UNKNOWN_ERROR(201001, "Unknown error. "), 38 | 39 | /** 40 | * input null. 41 | */ 42 | INPUT_NULL(201002, "Input parameter contains null value or missing keys. "), 43 | 44 | /** 45 | * input illegal. 46 | */ 47 | INPUT_ILLEGAL(201003, 48 | "One or more input arguments format illegal. Please refer to the API documents. "), 49 | 50 | /** 51 | * function name unknown. 52 | */ 53 | FUNCTION_NAME_ILLEGAL(201004, "Function name format illegal or missing. "), 54 | 55 | /** 56 | * transaction hex error. 57 | */ 58 | TXN_HEX_ERROR(201005, "Transaction hex creation failed. "), 59 | 60 | /** 61 | * transaction encoder error. 62 | */ 63 | TXN_ENCODER_ERROR(201006, "Transaction encoder creation failed. "), 64 | 65 | /** 66 | * SDK call error. 67 | */ 68 | WEID_SDK_ERROR(201007, "WeIdentity SDK call failed due to unknown error. "), 69 | 70 | /** 71 | * invoker weId is illegal. 72 | */ 73 | INVOKER_ILLEGAL(201008, "Cannot find the private key by the invoker index. "), 74 | 75 | /** 76 | * Nonce value illegal. 77 | */ 78 | NONCE_ILLEGAL(201009, "Nonce value illegal. "), 79 | 80 | /** 81 | * function arg illegal. 82 | */ 83 | FUNCARG_ILLEGAL(201010, "Function arguments format illegal or missing. "), 84 | 85 | /** 86 | * txn arg illegal. 87 | */ 88 | TXNARG_ILLEGAL(201011, "Transaction arguments format illegal or missing. "), 89 | 90 | /** 91 | * version illegal. 92 | */ 93 | VER_ILLEGAL(201012, "Version format illegal or missing. "), 94 | 95 | /** 96 | * signed message illegal. 97 | */ 98 | SIGNED_MSG_ILLEGAL(201013, "Signed message format illegal or missing. "), 99 | 100 | /** 101 | * data illegal. 102 | */ 103 | DATA_ILLEGAL(201014, "data segment format illegal or missing. "), 104 | 105 | /** 106 | * web3j error. 107 | */ 108 | WEB3J_ERROR(201015, "Failed to load web3j (maybe from illegal certs, Group ID, networking, or secp256k1 settings)"), 109 | 110 | /** 111 | * contract error. 112 | */ 113 | CONTRACT_ERROR(201016, "Failed to load contract (maybe from un-deployed site, DB not storing CNS, or CNS hash illegal)"), 114 | 115 | /** 116 | * BlockLimit value illegal. 117 | */ 118 | BLOCK_LIMIT_ILLEGAL(201017, "BlockLimit value illegal. "), 119 | 120 | /** 121 | * Convert a public key to a WeIdentity DID error 122 | */ 123 | CONVERT_PUBKEY_TO_WEID_ERROR(201018, "Convert public key to weId error. "), 124 | 125 | /** 126 | * SignType value illegal. 127 | */ 128 | SIGN_TYPE_ILLEGAL(201019, "SignType value illegal. "), 129 | 130 | /** 131 | * WeIdentity deploy style(database) not support send rawTransaction. 132 | */ 133 | WEIDENTITY_DEPLOY_NOT_SUPPORT(201019, "WeIdentity deploy style(database) not support send rawTransaction. "), 134 | 135 | /** 136 | * getWeIdListByPubKeyList interface error 137 | */ 138 | GET_WEID_LIST_BY_PUBKEY_LIST_ERROR(500100, "Get weId list by pubKeyList error. "), 139 | 140 | /** 141 | * RPC related error codes. 142 | */ 143 | RPC_SEND_FAIL(205001, "Sending RPC request failure"), 144 | RPC_NETWORK_ERROR(205002, "RPC networking failure"), 145 | RPC_GET_FAIL(205003, "Get RPC reply from request UUID failure"), 146 | RPC_FETCH_FAIL(205004, "Fetching RPC remote service info failure"), 147 | RPC_ENDPOINT_NOT_EXIST(205005, "RPC Endpoint does not exist"); 148 | 149 | /** 150 | * error code. 151 | */ 152 | private int code; 153 | 154 | /** 155 | * error message. 156 | */ 157 | private String codeDesc; 158 | 159 | /** 160 | * Error Code Constructor. 161 | * 162 | * @param code The ErrorCode 163 | * @param codeDesc The ErrorCode Description 164 | */ 165 | HttpReturnCode(int code, String codeDesc) { 166 | this.code = code; 167 | this.codeDesc = codeDesc; 168 | } 169 | 170 | /** 171 | * Get the Error Code. 172 | * 173 | * @return the ErrorCode 174 | */ 175 | public int getCode() { 176 | return code; 177 | } 178 | 179 | /** 180 | * Set the Error Code. 181 | * 182 | * @param code the new ErrorCode 183 | */ 184 | protected void setCode(int code) { 185 | this.code = code; 186 | } 187 | 188 | /** 189 | * Gets the ErrorCode Description. 190 | * 191 | * @return the ErrorCode Description 192 | */ 193 | public String getCodeDesc() { 194 | return codeDesc; 195 | } 196 | 197 | /** 198 | * Sets the ErrorCode Description. 199 | * 200 | * @param codeDesc the new ErrorCode Description 201 | */ 202 | protected void setCodeDesc(String codeDesc) { 203 | this.codeDesc = codeDesc; 204 | } 205 | } 206 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/constant/SignType.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.constant; 2 | 3 | public enum SignType { 4 | 5 | RSV(1), VSR(2); 6 | 7 | private int code; 8 | 9 | SignType(int code) { 10 | this.code = code; 11 | } 12 | 13 | public int getCode() { 14 | return code; 15 | } 16 | 17 | public static SignType getSignTypeByCode(int code) { 18 | for (SignType signType : SignType.values()) { 19 | if (code == signType.getCode()) { 20 | return signType; 21 | } 22 | } 23 | return null; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/constant/WalletAgentFunctionNames.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019-2020) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.constant; 21 | 22 | /** 23 | * Define function names to be picked for calls to WeIdentity Java SDK 24 | * 25 | * @author chaoxinhu 26 | **/ 27 | 28 | public final class WalletAgentFunctionNames { 29 | 30 | /** 31 | * Function names to be compared against the passed in encode/send transaction parameters. Case 32 | * insensitive. 33 | */ 34 | public static final String FUNCNAME_WALLETAGENT_CONSTRUCT = "construct"; 35 | public static final String FUNCNAME_WALLETAGENT_ISSUE = "issue"; 36 | public static final String FUNCNAME_WALLETAGENT_CONSTRUCTANDISSUE = "constructAndIssue"; 37 | public static final String FUNCNAME_WALLETAGENT_GETBALANCE = "getBalance"; 38 | public static final String FUNCNAME_WALLETAGENT_GETBATCHBALANCE = "getBatchBalance"; 39 | public static final String FUNCNAME_WALLETAGENT_GETBALANCEBYWEID = "getBalanceByWeId"; 40 | public static final String FUNCNAME_WALLETAGENT_SEND = "send"; 41 | public static final String FUNCNAME_WALLETAGENT_BATCHSEND = "batchSend"; 42 | public static final String FUNCNAME_WALLETAGENT_GETBASEINFO = "getBaseInfo"; 43 | public static final String FUNCNAME_WALLETAGENT_GETBASEINFOBYWEID = "getBaseInfoByWeId"; 44 | 45 | public static final String FUNCNAME_WALLETAGENT_BATCHISSUE = "batchIssue"; 46 | public static final String FUNCNAME_WALLETAGENT_CONSTRUCTANDBATCHISSUE = "constructAndBatchIssue"; 47 | public static final String FUNCNAME_WALLETAGENT_QUERYASSETOWNER = "queryAssetOwner"; 48 | public static final String FUNCNAME_WALLETAGENT_QUERYASSETNUM = "queryAssetNum"; 49 | public static final String FUNCNAME_WALLETAGENT_QUERYASSETLIST = "queryAssetList"; 50 | public static final String FUNCNAME_WALLETAGENT_QUERYOWNEDASSETNUM = "queryOwnedAssetNum"; 51 | public static final String FUNCNAME_WALLETAGENT_QUERYOWNEDASSETLIST = "queryOwnedAssetList"; 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/constant/WeIdentityFunctionNames.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.constant; 21 | 22 | import java.util.HashMap; 23 | import java.util.Map; 24 | 25 | /** 26 | * Define function names to be picked for calls to WeIdentity Java SDK 27 | * 28 | * @author chaoxinhu 29 | **/ 30 | 31 | public final class WeIdentityFunctionNames { 32 | 33 | /** 34 | * Function names to be compared against the passed in encode/send transaction parameters. Case 35 | * insensitive. 36 | */ 37 | public static final String FUNCNAME_CREATE_WEID = "createWeId"; 38 | public static final String FUNCNAME_CREATE_WEID_AND_RETURN_DOC = "createWeId2"; 39 | public static final String FUNCNAME_REGISTER_AUTHORITY_ISSUER = "registerAuthorityIssuer"; 40 | public static final String FUNCNAME_REGISTER_CPT = "registerCpt"; 41 | public static final String FUNCNAME_CREATE_CREDENTIAL = "createCredential"; 42 | public static final String FUNCNAME_VERIFY_CREDENTIAL = "verifyCredential"; 43 | public static final String FUNCNAME_GET_WEID_DOCUMENT = "getWeIdDocument"; 44 | public static final String FUNCNAME_GET_WEID_DOCUMENT_JSON = "getWeIdDocumentJson"; 45 | public static final String FUNCNAME_QUERY_AUTHORITY_ISSUER = "queryAuthorityIssuer"; 46 | public static final String FUNCNAME_QUERY_CPT = "queryCpt"; 47 | public static final String FUNCNAME_CREATE_CREDENTIALPOJO = "createCredentialPojo"; 48 | public static final String FUNCNAME_VERIFY_CREDENTIALPOJO = "verifyCredentialPojo"; 49 | 50 | public static final String FUNCNAME_CREATE_WEID_WITH_PUBKEY = "createWeIdWithPubKey"; 51 | public static final String FUNCNAME_CREATE_WEID_WITH_PUBKEY_AND_RETURN_DOC = "createWeIdWithPubKey2"; 52 | public static final String FUNCNAME_GET_WEID_DOCUMENT_BY_ORG = "getWeIdDocumentByOrgId"; 53 | public static final String FUNCNAME_VERIFY_LITE_CREDENTIAL = "verifyLiteCredential"; 54 | public static final String FUNCNAME_CREATE_EVIDENCE_FOR_LITE_CREDENTIAL = "createEvidence"; 55 | public static final String FUNCNAME_CREATE_EVIDENCE_FOR_LITE_CREDENTIAL_DELEGATE = "delegateCreateEvidence"; 56 | public static final String FUNCNAME_CREATE_EVIDENCE_FOR_LITE_CREDENTIAL_DELEGATE_BATCH = "delegateCreateEvidenceB"; 57 | public static final String FUNCNAME_ECCENCRYPT_CREDENTIAL = "createCredentialAndEncrypt"; 58 | public static final String FUNCNAME_ECCDECRYPT = "eccDecrypt"; 59 | public static final String FUNCNAME_ECCENCRYPT = "eccEncrypt"; 60 | public static final String FUNCNAME_GET_EVIDENCE_BY_HASH = "getEvidence"; 61 | public static final String FUNCNAME_ADD_WEID_TO_WHITELIST = "addWeIdToWhitelist"; 62 | public static final String FUNCNAME_IS_WEID_IN_WHITELIST = "isWeIdInWhitelist"; 63 | public static final String FUNCNAME_RECOGNIZE_AUTHORITY_ISSUER = "recognizeAuthorityIssuer"; 64 | public static final String FUNCNAME_DERECOGNIZE_AUTHORITY_ISSUER = "deRecognizeAuthorityIssuer"; 65 | public static final String FUNCNAME_GETWEIDLIST_BYPUBKEYLIST = "getWeIdListByPubKeyList"; 66 | /** 67 | * Function names to be assembled in SDK Function call. Case sensitive. FISCO-BCOS v1. 68 | */ 69 | public static final String FUNCCALL_UPDATE_WEID = "updateWeId"; 70 | public static final String FUNCCALL_ADD_AUTHORITY_ISSUER = "addAuthorityIssuer"; 71 | public static final String FUNCCALL_REGISTER_CPT = "registerCpt"; 72 | 73 | /** 74 | * The FISCO-BCOS v2 function name and call map. 75 | */ 76 | public static final Map FUNCNAME_CALL_MAP_V2 = new HashMap() {{ 77 | put(FUNCNAME_CREATE_WEID, "createWeId"); 78 | put(FUNCNAME_REGISTER_AUTHORITY_ISSUER, "addAuthorityIssuer"); 79 | put(FUNCNAME_REGISTER_CPT, "registerCpt"); 80 | }}; 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/constant/WeIdentityParamKeyConstant.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.constant; 21 | 22 | /** 23 | * Define param key names to be allowed to enable calls to WeIdentity Java SDK 24 | * 25 | * @author chaoxinhu 26 | **/ 27 | public final class WeIdentityParamKeyConstant { 28 | 29 | /** 30 | * Universal param key names. Treated as case-INSENSITIVE when being checked. 31 | */ 32 | public static final String FUNCTION_NAME = "functionName"; 33 | public static final String TRANSACTION_DATA = "data"; 34 | public static final String BLOCK_LIMIT = "blockLimit"; 35 | public static final String SIGN_TYPE = "signType"; 36 | public static final String SIGNED_MESSAGE = "signedMessage"; 37 | public static final String API_VERSION = "v"; 38 | public static final String NONCE = "nonce"; 39 | public static final String FUNCTION_ARG = "functionArg"; 40 | public static final String TRANSACTION_ARG = "transactionArg"; 41 | public static final String CLAIM_HASH = "claimHash"; 42 | public static final String KEY_INDEX = "invokerWeId"; 43 | public static final String LOOP_BACK = "loopback"; 44 | public static final String BODY = "body"; 45 | public static final String LIST = "list"; 46 | 47 | public static final String DEFAULT_API_VERSION = "1.0.0"; 48 | public static final String DEFAULT_PRIVATE_KEY_FILE_NAME = "private_key"; 49 | 50 | public static final String AUTHO_TOKEN = "authToken"; 51 | public static final String AUTHO_SIGNED_NONCE = "signedNonce"; 52 | 53 | public static final String ORG_ID = "orgId"; 54 | public static final String CREDENTIAL_ID = "id"; 55 | public static final String HASH = "hash"; 56 | public static final String PROOF = "proof"; 57 | public static final String SIGN = "sign"; 58 | public static final String LOG = "log"; 59 | public static final String PUBKEY_ECDSA = "publicKeyECDSA"; 60 | public static final String PUBKEY_LIST = "publicKeyList"; 61 | public static final String PUBKEY_SM2 = "publicKeySM2"; 62 | 63 | public static final String WHITELIST_NAME = "whitelistName"; 64 | 65 | public static final String GROUP_ID = "groupId"; 66 | public static final String HASH_VALUE = "hashValue"; 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/constant/WeIdentityServiceEndpoint.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.constant; 21 | 22 | /** 23 | * Define function names to be picked for calls to WeIdentity Java SDK 24 | * 25 | * @author chaoxinhu 26 | **/ 27 | 28 | public final class WeIdentityServiceEndpoint { 29 | 30 | /** 31 | * API endpoint. 32 | */ 33 | public static final String API_ROOT = "weid/api"; 34 | public static final String PAYMENT_ROOT = "payment"; 35 | public static final String ENCODE_TRANSACTION = "encode"; 36 | public static final String SEND_TRANSACTION = "transact"; 37 | public static final String INVOKE_FUNCTION = "invoke"; 38 | public static final String WALLET_AGENT_BAC004_FUNCTION = "bac004/api/invoke"; 39 | public static final String WALLET_AGENT_BAC005_FUNCTION = "bac005/api/invoke"; 40 | public static final String WALLET_AGENT_BAC004_FUNCTION_ENCODE = "bac004/api/encode"; 41 | public static final String WALLET_AGENT_BAC004_FUNCTION_TRANSACT = "bac004/api/transact"; 42 | public static final String WALLET_AGENT_BAC005_FUNCTION_ENCODE = "bac005/api/encode"; 43 | public static final String WALLET_AGENT_BAC005_FUNCTION_TRANSACT = "bac005/api/transact"; 44 | 45 | /** 46 | * EP Service endpoint. 47 | */ 48 | public static final String EPS_ROOT = "endpoint"; 49 | public static final String ADD_FUNCTION = "add"; 50 | public static final String REMOVE_FUNCTION = "remove"; 51 | public static final String FETCH_FUNCTION = "auto-fetch"; 52 | 53 | /** 54 | * Data-Authorization related endpoints. 55 | */ 56 | public static final String AUTHO_ROOT = "authorize"; 57 | public static final String AUTHO_FETCH_DATA = "fetch-data"; 58 | public static final String AUTHO_REQUEST_NONCE = "request-nonce"; 59 | 60 | /** 61 | * Separator. 62 | */ 63 | public static final String EPS_SEPARATOR = "|||"; 64 | 65 | /** 66 | * Misc items 67 | */ 68 | public static final String ALL_INFO = "ALL"; 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/protocol/base/ResolutionMetadata.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.protocol.base; 2 | 3 | import lombok.Data; 4 | /** 5 | * The base data structure to handle WeId Resolution Metadata. 6 | * 7 | * @author afeexian 2022.9.29 8 | */ 9 | @Data 10 | public class ResolutionMetadata { 11 | /** 12 | * Media Type of the returned WeId Document Stream, WeId currently support JSON-LD. 13 | */ 14 | private String contentType; 15 | /** 16 | * error message. 17 | */ 18 | private String error; 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/protocol/base/ResolveData.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.protocol.base; 2 | 3 | import com.webank.weid.protocol.base.WeIdDocument; 4 | import com.webank.weid.protocol.base.WeIdDocumentMetadata; 5 | import lombok.Data; 6 | 7 | /** 8 | * The base data structure to handle WeIdentity DID Document and DocumentMetadata info. 9 | * 10 | * @author afeexian 2022.9.29 11 | */ 12 | @Data 13 | public class ResolveData { 14 | 15 | /** 16 | * Resolution Metadata. 17 | */ 18 | private ResolutionMetadata resolutionMetadata; 19 | /** 20 | * WeId Document. 21 | */ 22 | private WeIdDocument weIdDocument; 23 | 24 | /** 25 | * WeId Document Metadata. 26 | */ 27 | WeIdDocumentMetadata weIdDocumentMetadata; 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/protocol/base/ResolveDataJsonLD.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.protocol.base; 2 | 3 | import com.webank.weid.protocol.base.WeIdDocument; 4 | import com.webank.weid.protocol.base.WeIdDocumentMetadata; 5 | import lombok.Data; 6 | 7 | /** 8 | * The base data structure to handle WeIdentity DID DocumentStream in json-ld and DocumentMetadata info. 9 | * 10 | * @author afeexian 2022.9.29 11 | */ 12 | @Data 13 | public class ResolveDataJsonLD { 14 | /** 15 | * Resolution Metadata. 16 | */ 17 | private ResolutionMetadata resolutionMetadata; 18 | /** 19 | * WeId Document. 20 | */ 21 | private String weIdDocumentJson; 22 | 23 | /** 24 | * WeId Document Metadata. 25 | */ 26 | WeIdDocumentMetadata weIdDocumentMetadata; 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/protocol/request/EndpointRequest.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.protocol.request; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class EndpointRequest { 7 | 8 | private String requestName; 9 | private String requestBody; 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/protocol/request/InputArg.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.protocol.request; 21 | 22 | import lombok.Data; 23 | 24 | /** 25 | * The common input argument for all Service API. 26 | * 27 | * @author chaoxinhu 28 | **/ 29 | @Data 30 | public class InputArg { 31 | 32 | /** 33 | * Required: the function related arguments. 34 | */ 35 | String functionArg; 36 | 37 | /** 38 | * Required: the transaction related arguments. 39 | */ 40 | String transactionArg; 41 | 42 | /** 43 | * Required: the function name to be called. 44 | */ 45 | String functionName; 46 | 47 | /** 48 | * Required: the API version. 49 | */ 50 | String v; 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/protocol/request/ReqInput.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.protocol.request; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class ReqInput { 7 | /** 8 | * Required: the function related arguments. 9 | */ 10 | F functionArg; 11 | 12 | /** 13 | * Required: the transaction related arguments. 14 | */ 15 | TransactionArg transactionArg; 16 | 17 | /** 18 | * Required: the function name to be called. 19 | */ 20 | String functionName; 21 | 22 | /** 23 | * Required: the API version. 24 | */ 25 | String v; 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/protocol/request/TransactionArg.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.protocol.request; 2 | 3 | import com.webank.weid.http.constant.SignType; 4 | 5 | import lombok.Data; 6 | 7 | @Data 8 | public class TransactionArg { 9 | 10 | String invokerWeId; 11 | String nonce; 12 | String data; 13 | String signedMessage; 14 | String toAddress; 15 | Object loopback; 16 | String blockLimit; 17 | int signType; 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/protocol/request/payment/AssetAddressList.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.protocol.request.payment; 2 | 3 | import java.util.List; 4 | 5 | import lombok.Data; 6 | 7 | @Data 8 | public class AssetAddressList { 9 | private String assetHolder; 10 | private List assetAddressList; 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/protocol/request/payment/BAC004BatchSendInfo.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.protocol.request.payment; 2 | 3 | import java.util.List; 4 | 5 | import com.webank.payment.protocol.base.BaseAsset; 6 | 7 | import lombok.Data; 8 | import lombok.EqualsAndHashCode; 9 | import lombok.ToString; 10 | 11 | @Data 12 | @ToString(callSuper = true) 13 | @EqualsAndHashCode(callSuper = true) 14 | public class BAC004BatchSendInfo extends BaseAsset { 15 | 16 | private List list; 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/protocol/request/payment/BAC004Info.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.protocol.request.payment; 2 | 3 | import com.webank.payment.protocol.base.BaseBACInfo; 4 | 5 | import lombok.Data; 6 | import lombok.EqualsAndHashCode; 7 | import lombok.ToString; 8 | 9 | @Data 10 | @ToString(callSuper = true) 11 | @EqualsAndHashCode(callSuper = true) 12 | public class BAC004Info extends BaseBACInfo { 13 | private String recipient; 14 | private String remark; 15 | private Integer amount; 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/protocol/request/payment/BAC004SendInfo.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.protocol.request.payment; 2 | 3 | import com.webank.payment.protocol.base.BaseAsset; 4 | 5 | import lombok.Data; 6 | import lombok.EqualsAndHashCode; 7 | import lombok.ToString; 8 | 9 | @Data 10 | @ToString(callSuper = true) 11 | @EqualsAndHashCode(callSuper = true) 12 | public class BAC004SendInfo extends BaseAsset { 13 | private String recipient; 14 | private String remark; 15 | private Integer amount; 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/protocol/request/payment/BAC005BatchInfo.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.protocol.request.payment; 2 | 3 | import com.webank.payment.protocol.base.BaseBACInfo; 4 | import lombok.Data; 5 | import lombok.EqualsAndHashCode; 6 | import lombok.ToString; 7 | 8 | import java.util.List; 9 | 10 | @Data 11 | @ToString(callSuper = true) 12 | @EqualsAndHashCode(callSuper = true) 13 | public class BAC005BatchInfo extends BaseBACInfo { 14 | 15 | private List list; 16 | 17 | private String remark; 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/protocol/request/payment/BAC005Info.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.protocol.request.payment; 2 | 3 | import com.webank.payment.protocol.base.BaseBACInfo; 4 | import lombok.Data; 5 | import lombok.EqualsAndHashCode; 6 | import lombok.ToString; 7 | 8 | @Data 9 | @ToString(callSuper = true) 10 | @EqualsAndHashCode(callSuper = true) 11 | public class BAC005Info extends BaseBACInfo { 12 | private String recipient; 13 | private String remark; 14 | private Integer assetId; 15 | private String assetUri; 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/protocol/request/payment/BaseQuery.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.protocol.request.payment; 2 | 3 | import com.webank.payment.protocol.base.BaseAsset; 4 | 5 | import lombok.Data; 6 | import lombok.EqualsAndHashCode; 7 | import lombok.ToString; 8 | 9 | @Data 10 | @ToString(callSuper = true) 11 | @EqualsAndHashCode(callSuper = true) 12 | public class BaseQuery extends BaseAsset { 13 | private String assetHolder; 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/protocol/request/payment/PageQuery.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.protocol.request.payment; 2 | 3 | import lombok.Data; 4 | import lombok.EqualsAndHashCode; 5 | import lombok.ToString; 6 | 7 | @Data 8 | @ToString(callSuper = true) 9 | @EqualsAndHashCode(callSuper = true) 10 | public class PageQuery extends BaseQuery{ 11 | // private Integer amount; 12 | private Integer index; 13 | private Integer num; 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/protocol/response/EncodedTransactionWrapper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.protocol.response; 21 | 22 | import lombok.Data; 23 | 24 | /** 25 | * The result of EncodedTransaction. A wrapper class with both encoded String, and rawTransaction. 26 | * 27 | * @author chaoxinhu 28 | */ 29 | 30 | @Data 31 | public class EncodedTransactionWrapper { 32 | 33 | /** 34 | * The Encoded Transaction in String. This MUST be in Base64 format. 35 | */ 36 | private String encodedTransaction; 37 | 38 | /** 39 | * The data segment instance in RawTransaction. Client needs this for future sendTransaction. 40 | */ 41 | private String data; 42 | 43 | private String blockLimit; 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/protocol/response/EndpointInfo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.protocol.response; 21 | 22 | import java.util.List; 23 | 24 | import lombok.Data; 25 | 26 | @Data 27 | public class EndpointInfo { 28 | 29 | private String requestName; 30 | private List inAddr; 31 | private String description; 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/protocol/response/HttpResponseData.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.protocol.response; 21 | 22 | import lombok.Data; 23 | 24 | import com.webank.weid.http.constant.HttpReturnCode; 25 | 26 | /** 27 | * The internal base response result class. 28 | * 29 | * @param the generic type 30 | * @author tonychen and chaoxinhu 31 | */ 32 | @Data 33 | public class HttpResponseData { 34 | 35 | private T respBody; 36 | private Object loopback; 37 | private Integer errorCode; 38 | private String errorMessage; 39 | 40 | /** 41 | * Instantiates a new response data. 42 | */ 43 | public HttpResponseData() { 44 | this.setErrorCode(HttpReturnCode.SUCCESS); 45 | } 46 | 47 | /** 48 | * Instantiates a new response data. 49 | * 50 | * @param result the result 51 | * @param errorCode the return code 52 | */ 53 | public HttpResponseData(T result, HttpReturnCode errorCode) { 54 | this.respBody = result; 55 | this.errorCode = errorCode.getCode(); 56 | this.errorMessage = errorCode.getCodeDesc(); 57 | } 58 | 59 | /** 60 | * Instantiates a new response data. 61 | * 62 | * @param result the result 63 | * @param loopback the loopback 64 | * @param errorCode the return code 65 | */ 66 | public HttpResponseData(T result, Object loopback, HttpReturnCode errorCode) { 67 | this.respBody = result; 68 | this.loopback = loopback; 69 | this.errorCode = errorCode.getCode(); 70 | this.errorMessage = errorCode.getCodeDesc(); 71 | } 72 | 73 | /** 74 | * Instantiates a new response data by inputing all params. 75 | * 76 | * @param result the result 77 | * @param errorCode the error code 78 | * @param errorMessage the error msg 79 | */ 80 | public HttpResponseData(T result, Integer errorCode, String errorMessage) { 81 | this.respBody = result; 82 | this.errorCode = errorCode; 83 | this.errorMessage = errorMessage; 84 | } 85 | 86 | /** 87 | * Instantiates a new response data by inputing all params. 88 | * 89 | * @param result the result 90 | * @param loopback the loopback 91 | * @param errorCode the error code 92 | * @param errorMessage the error msg 93 | */ 94 | public HttpResponseData(T result, Object loopback, Integer errorCode, String errorMessage) { 95 | this.respBody = result; 96 | this.loopback = loopback; 97 | this.errorCode = errorCode; 98 | this.errorMessage = errorMessage; 99 | } 100 | 101 | /** 102 | * set a ErrorCode type errorCode. 103 | */ 104 | public void setErrorCode(HttpReturnCode errorCode) { 105 | this.errorCode = errorCode.getCode(); 106 | this.errorMessage = errorCode.getCodeDesc(); 107 | } 108 | 109 | } -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/protocol/response/WeIdListRsp.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.protocol.response; 2 | 3 | import java.util.List; 4 | import lombok.Data; 5 | 6 | /** 7 | * get WeId and errorCode by pubkeyList response. 8 | * 9 | */ 10 | 11 | @Data 12 | public class WeIdListRsp { 13 | 14 | private List weIdList; 15 | 16 | private List errorCodeList; 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/service/AuthService.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.service; 2 | 3 | import com.webank.weid.http.protocol.response.HttpResponseData; 4 | import com.webank.weid.protocol.base.CredentialPojo; 5 | import org.springframework.stereotype.Service; 6 | 7 | @Service 8 | public interface AuthService { 9 | 10 | /** 11 | * Process data fetching from a service URL based on the CPT101 authorization 12 | * credential and client-side signing of a nonce from http-server. 13 | * 14 | * @return remote data in String format 15 | */ 16 | HttpResponseData fetchData(CredentialPojo authToken, String signedNonce); 17 | 18 | /** 19 | * Request a data fetch nonce from http server. TODO to-be-implemented. 20 | * 21 | * @return token in String format 22 | */ 23 | HttpResponseData requestNonce(CredentialPojo authToken); 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/service/BaseService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.service; 21 | 22 | import com.webank.weid.blockchain.rpc.RawTransactionService; 23 | import com.webank.weid.blockchain.service.impl.RawTransactionServiceImpl; 24 | import com.webank.weid.constant.ErrorCode; 25 | import com.webank.weid.http.protocol.request.TransactionArg; 26 | import com.webank.weid.http.protocol.response.HttpResponseData; 27 | import com.webank.weid.http.util.PropertiesUtil; 28 | import com.webank.weid.service.rpc.WeIdService; 29 | import com.webank.weid.util.PropertyUtils; 30 | import org.apache.commons.lang3.StringUtils; 31 | import org.slf4j.Logger; 32 | import org.slf4j.LoggerFactory; 33 | import org.springframework.context.ApplicationContext; 34 | import org.springframework.context.support.ClassPathXmlApplicationContext; 35 | 36 | 37 | import com.webank.payment.protocol.base.Authentication; 38 | import com.webank.payment.protocol.base.PrivateKey; 39 | import com.webank.weid.exception.WeIdBaseException; 40 | import com.webank.weid.http.constant.HttpReturnCode; 41 | import com.webank.weid.http.util.KeyUtil; 42 | import com.webank.weid.util.DataToolUtils; 43 | import com.webank.weid.util.WeIdUtils; 44 | 45 | public abstract class BaseService { 46 | 47 | private static final Logger logger = LoggerFactory.getLogger(BaseService.class); 48 | 49 | /** 50 | * spring context. 51 | */ 52 | protected static final ApplicationContext context; 53 | 54 | public static RawTransactionService rawTransactionService; 55 | static { 56 | if (PropertyUtils.getProperty("deploy.style").equals("blockchain")) { 57 | rawTransactionService = new RawTransactionServiceImpl(); 58 | } 59 | } 60 | 61 | static { 62 | // initializing spring containers 63 | context = new ClassPathXmlApplicationContext(new String[]{ 64 | "classpath:SpringApplicationContext.xml"}); 65 | logger.info("initializing spring containers finish..."); 66 | 67 | } 68 | 69 | private PrivateKey buildPrivateKey(String value) { 70 | PrivateKey pri = new PrivateKey(); 71 | pri.setValue(value); 72 | return pri; 73 | } 74 | 75 | protected Authentication getAuthentication(String weId) { 76 | Authentication authentication = getAuthenticationByWeId(weId); 77 | String passphrase = PropertiesUtil.getProperty("default.passphrase"); 78 | if (StringUtils.isNotBlank(weId) && weId.equalsIgnoreCase(passphrase)) { 79 | //将私钥转换成公钥,将公钥转换成weId地址 80 | weId = WeIdUtils.getWeIdFromPrivateKey(authentication.getPrivateKey().getValue()); 81 | } 82 | authentication.setUserAddress(WeIdUtils.convertWeIdToAddress(weId)); 83 | return authentication; 84 | } 85 | 86 | private Authentication getAuthenticationByWeId(String weId) { 87 | String weIdPrivKey = KeyUtil 88 | .getPrivateKeyByWeId(KeyUtil.SDK_PRIVKEY_PATH, weId); 89 | if (StringUtils.isEmpty(weIdPrivKey)) { 90 | throw new WeIdBaseException(HttpReturnCode.INVOKER_ILLEGAL.getCodeDesc()); 91 | } 92 | Authentication authentication = new Authentication(); 93 | authentication.setPrivateKey(buildPrivateKey(weIdPrivKey)); 94 | return authentication; 95 | } 96 | 97 | protected HttpResponseData checkWeIdExist(WeIdService weIdService, String weId) { 98 | com.webank.weid.blockchain.protocol.response.ResponseData weIdExist = weIdService.isWeIdExist(weId); 99 | if (!weIdExist.getResult()) { 100 | return new HttpResponseData<>( 101 | weIdExist.getResult(), 102 | ErrorCode.WEID_DOES_NOT_EXIST.getCode(), 103 | "the weId:[" + weId + "] does not exist on blockchain." 104 | ); 105 | } 106 | return null; 107 | } 108 | 109 | protected static Object getLoopBack(String transactionArgStr) { 110 | TransactionArg transactionArg = DataToolUtils.deserialize(transactionArgStr, TransactionArg.class); 111 | return transactionArg.getLoopback(); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/service/EndpointService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.service; 21 | 22 | import java.util.List; 23 | 24 | import org.springframework.stereotype.Service; 25 | 26 | import com.webank.weid.http.protocol.request.EndpointRequest; 27 | import com.webank.weid.http.protocol.response.EndpointInfo; 28 | import com.webank.weid.http.protocol.response.HttpResponseData; 29 | 30 | @Service 31 | public interface EndpointService { 32 | 33 | /** 34 | * Get all registered endpoints. 35 | * @return 36 | */ 37 | HttpResponseData> getAllEndpoints(); 38 | 39 | /** 40 | * Re-route an endpoint service to SDK. 41 | * 42 | * @param endpointRequest 43 | * @return 44 | */ 45 | HttpResponseData invokeEndpointService(EndpointRequest endpointRequest); 46 | 47 | /** 48 | * Get an endpoint info. 49 | * 50 | * @param endpointName 51 | * @return 52 | */ 53 | HttpResponseData getEndpoint(String endpointName); 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/service/InvokeService.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.service; 2 | 3 | import com.webank.weid.http.protocol.response.HttpResponseData; 4 | 5 | public interface InvokeService { 6 | 7 | /** 8 | * Directly invoke an SDK function. No client-side sign needed. 9 | * 10 | * @param invokeFunctionJsonArgs the json format args. It should contain 4 keys: functionArgs, 11 | * (including all business related params), EMPTY transactionArgs, functionName and apiVersion. 12 | * @return the json string from SDK response. 13 | */ 14 | HttpResponseData invokeFunction(String invokeFunctionJsonArgs); 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/service/InvokerAuthorityIssuerService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.service; 21 | 22 | import org.springframework.stereotype.Service; 23 | 24 | import com.webank.weid.http.protocol.request.InputArg; 25 | import com.webank.weid.http.protocol.response.HttpResponseData; 26 | 27 | @Service 28 | public interface InvokerAuthorityIssuerService { 29 | 30 | /** 31 | * Register a new Authority Issuer on Chain via Invoke function. 32 | * 33 | * @param registerArgs the args 34 | * @return the Boolean response data 35 | */ 36 | HttpResponseData registerAuthorityIssuerInvoke(InputArg registerArgs); 37 | 38 | /** 39 | * Call to WeID SDK with direct transaction hex String, to register AuthorityIssuer. 40 | * 41 | * @param transactionHex the transactionHex value 42 | * @return String in ResponseData 43 | */ 44 | HttpResponseData registerAuthorityIssuerWithTransactionHex( 45 | String transactionHex); 46 | 47 | /** 48 | * Query Authority Issuer via the InvokeFunction API. 49 | * 50 | * @param queryArgs the query WeID 51 | * @return the authorityIssuer 52 | */ 53 | HttpResponseData queryAuthorityIssuerInfoInvoke(InputArg queryArgs); 54 | 55 | HttpResponseData getWeIdByNameInvoke(InputArg args); 56 | 57 | /** 58 | * Register Issuer Type on chain. 59 | * @param registerArgs the args 60 | * @return the Boolean response data 61 | */ 62 | HttpResponseData addWeIdToWhitelist(InputArg args); 63 | 64 | /** 65 | * Check weId is exists in IssuerType on chain. 66 | * @param CheckArgs the args 67 | * @return the Boolean response data 68 | */ 69 | HttpResponseData isWeIdInWhitelist(InputArg args); 70 | 71 | HttpResponseData recognizeAuthorityIssuer(InputArg args); 72 | 73 | HttpResponseData deRecognizeAuthorityIssuer(InputArg args); 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/service/InvokerCptService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.service; 21 | 22 | import org.springframework.stereotype.Service; 23 | 24 | import com.webank.weid.http.protocol.request.InputArg; 25 | import com.webank.weid.http.protocol.response.HttpResponseData; 26 | 27 | @Service 28 | public interface InvokerCptService { 29 | 30 | /** 31 | * Register a new CPT to blockchain via Invoke function. 32 | * 33 | * @param registerArgs the args 34 | * @return the resp data 35 | */ 36 | HttpResponseData registerCptInvoke(InputArg registerArgs); 37 | 38 | /** 39 | * Call to WeID SDK with direct transaction hex String, to register CPT. 40 | * 41 | * @param transactionHex the transactionHex value 42 | * @return String in ResponseData 43 | */ 44 | HttpResponseData registerCptWithTransactionHex(String transactionHex); 45 | 46 | /** 47 | * Query CPT via the InvokeFunction API. 48 | * 49 | * @param queryArgs the query arg 50 | * @return the CPT data 51 | */ 52 | HttpResponseData queryCptInvoke(InputArg queryArgs); 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/service/InvokerCredentialService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.service; 21 | 22 | import org.springframework.stereotype.Service; 23 | 24 | import com.webank.weid.http.protocol.request.InputArg; 25 | import com.webank.weid.http.protocol.response.HttpResponseData; 26 | 27 | @Service 28 | public interface InvokerCredentialService { 29 | 30 | /** 31 | * Generate a credential for client to sign. The signature field is null, and both full claim 32 | * and claimHash will be returned. The returned json String is an key-ordered compact json. 33 | * 34 | * @param createCredentialFuncArgs the functionArgs 35 | * @return the Map contains Credential content and claimHash. 36 | */ 37 | HttpResponseData createCredentialInvoke(InputArg createCredentialFuncArgs); 38 | 39 | /** 40 | * Verify the validity of a credential. Need format conversion (UTC date and @context) 41 | * 42 | * @param verifyCredentialFuncArgs the credential json args 43 | * @return the Boolean response data 44 | */ 45 | HttpResponseData verifyCredentialInvoke(InputArg verifyCredentialFuncArgs); 46 | 47 | /** 48 | * Create Credential Pojo. Need format conversion. 49 | * 50 | * @param createCredentialPojoFuncArgs 51 | * @return credentialpojo 52 | */ 53 | HttpResponseData createCredentialPojoInvoke(InputArg createCredentialPojoFuncArgs); 54 | 55 | HttpResponseData createCredentialPojoAndEncryptInvoke(InputArg createCredentialPojoFuncArgs); 56 | 57 | HttpResponseData eccEncrypt(InputArg encryptFuncArgs); 58 | 59 | HttpResponseData eccDecrypt(InputArg decryptFuncArgs); 60 | 61 | /** 62 | * Verify the validity of a Credential Pojo. Need format conversion. 63 | * 64 | * @param verifyCredentialPojoFuncArgs 65 | * @return boolean 66 | */ 67 | HttpResponseData verifyCredentialPojoInvoke(InputArg verifyCredentialPojoFuncArgs); 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/service/InvokerEvidenceService.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.service; 2 | 3 | import com.webank.weid.http.protocol.request.InputArg; 4 | import com.webank.weid.http.protocol.response.HttpResponseData; 5 | import org.springframework.stereotype.Service; 6 | 7 | @Service 8 | public interface InvokerEvidenceService { 9 | 10 | HttpResponseData createEvidenceWithExtraInfo(InputArg args); 11 | 12 | HttpResponseData delegateCreateEvidence(InputArg args); 13 | 14 | HttpResponseData delegateCreateEvidenceBatch(InputArg args); 15 | 16 | HttpResponseData getEvidenceByCustomKey(InputArg args); 17 | 18 | HttpResponseData getEvidenceByHash(InputArg args); 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/service/InvokerWeIdService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.service; 21 | 22 | import org.springframework.stereotype.Service; 23 | 24 | import com.webank.weid.http.protocol.request.InputArg; 25 | import com.webank.weid.http.protocol.response.HttpResponseData; 26 | import com.webank.weid.protocol.response.CreateWeIdDataResult; 27 | import com.webank.weid.blockchain.protocol.response.ResponseData; 28 | 29 | @Service 30 | public interface InvokerWeIdService { 31 | 32 | /** 33 | * Create WeIdentity DID - a raw method for test purpose only. 34 | * 35 | * @return the response data 36 | */ 37 | ResponseData createWeId(); 38 | 39 | /** 40 | * Check if WeIdentity DID exists on Chain - for test purpose only. 41 | * 42 | * @param weId the WeIdentity DID 43 | * @return true if exists, false otherwise 44 | */ 45 | ResponseData isWeIdExist(String weId); 46 | 47 | /** 48 | * Call to WeID SDK with direct transaction hex String, to create WeID. 49 | * 50 | * @param transactionHex the transactionHex value 51 | * @return String in ResponseData 52 | */ 53 | HttpResponseData createWeIdWithTransactionHex(String transactionHex); 54 | 55 | /** 56 | * Get a WeIdentity DID DocumentStream in Json-ld via the InvokeFunction API. 57 | * 58 | * @param getWeIdDocumentJsonArgs the WeIdentity DID 59 | * @return the WeIdentity DID document json 60 | */ 61 | HttpResponseData getWeIdDocumentJsonInvoke(InputArg getWeIdDocumentJsonArgs); 62 | 63 | /** 64 | * Get a WeIdentity DID Document via the InvokeFunction API. 65 | * 66 | * @param getWeIdDocumentArgs the WeIdentity DID 67 | * @return the WeIdentity DID document json 68 | */ 69 | HttpResponseData getWeIdDocumentInvoke(InputArg getWeIdDocumentArgs); 70 | 71 | /** 72 | * Create WeId via the InvokeFunction API. 73 | * 74 | * @param createWeIdJsonArgs the input args, should be almost null 75 | * @return the WeIdentity DID 76 | */ 77 | HttpResponseData createWeIdInvoke(InputArg createWeIdJsonArgs); 78 | 79 | /** 80 | * Create WeId via the InvokeFunction API. 81 | * 82 | * @param createWeIdJsonArgs the input args, should be almost null 83 | * @return the WeIdentity DID 84 | */ 85 | HttpResponseData createWeIdInvoke2(InputArg createWeIdJsonArgs); 86 | 87 | HttpResponseData createWeIdWithPubKey(InputArg arg); 88 | 89 | HttpResponseData createWeIdWithPubKey2(InputArg arg); 90 | 91 | HttpResponseData getWeIdListByPubKeyList(InputArg arg) throws Exception ; 92 | } 93 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/service/RawTransaction.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.service; 2 | 3 | import com.webank.weid.http.protocol.response.HttpResponseData; 4 | 5 | public interface RawTransaction { 6 | 7 | /** 8 | * Create an Encoded Transaction. 9 | * 10 | * @param encodeTransactionJsonArgs json format args. It should contain 4 keys: functionArgs 11 | * (including all business related params), transactionArgs, functionName and apiVersion. 12 | * Hereafter, functionName will decide which WeID SDK method to engage, and assemble all input 13 | * params into SDK readable format to send there; apiVersion is for extensibility purpose. 14 | * @return encoded transaction in Base64 format, and the data segment in RawTransaction. 15 | */ 16 | HttpResponseData encodeTransaction(String encodeTransactionJsonArgs); 17 | 18 | /** 19 | * Send Transaction to Blockchain. 20 | * 21 | * @param sendTransactionJsonArgs the json format args. It should contain 4 keys: functionArgs 22 | * (including all business related params), transactionArgs, functionName and apiVersion. 23 | * @return the json string from SDK response. 24 | */ 25 | HttpResponseData sendTransaction(String sendTransactionJsonArgs); 26 | } 27 | 28 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/service/TransactionService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.service; 21 | 22 | import org.springframework.stereotype.Service; 23 | 24 | /** 25 | * Handling Transaction related services. 26 | * 27 | * @author chaoxinhu and darwindu 28 | **/ 29 | @Service 30 | public interface TransactionService extends InvokeService, RawTransaction { 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/service/impl/AuthServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.service.impl; 2 | 3 | import com.webank.weid.http.constant.HttpReturnCode; 4 | import com.webank.weid.http.protocol.request.EndpointRequest; 5 | import com.webank.weid.http.protocol.response.EndpointInfo; 6 | import com.webank.weid.http.protocol.response.HttpResponseData; 7 | import com.webank.weid.http.service.AuthService; 8 | import com.webank.weid.http.service.BaseService; 9 | import com.webank.weid.http.service.rpc.RpcConnectionHandler; 10 | import com.webank.weid.http.util.EndpointDataUtil; 11 | import com.webank.weid.protocol.base.CredentialPojo; 12 | import com.webank.weid.blockchain.protocol.response.ResponseData; 13 | import com.webank.weid.service.rpc.CredentialPojoService; 14 | import com.webank.weid.service.impl.CredentialPojoServiceImpl; 15 | import com.webank.weid.util.DataToolUtils; 16 | import java.net.URI; 17 | import java.util.List; 18 | import org.apache.commons.lang3.StringUtils; 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | import org.springframework.stereotype.Component; 22 | 23 | @Component 24 | public class AuthServiceImpl extends BaseService implements AuthService { 25 | 26 | private Logger logger = LoggerFactory.getLogger(AuthServiceImpl.class); 27 | private CredentialPojoService credentialPojoService = new CredentialPojoServiceImpl(); 28 | //private WeIdService weIdService = new WeIdServiceImpl(); 29 | 30 | static { 31 | RpcConnectionHandler.init(); 32 | } 33 | 34 | @Override 35 | public HttpResponseData requestNonce(CredentialPojo authToken) { 36 | ResponseData verifyResp = credentialPojoService.verify(authToken.getIssuer(), authToken); 37 | if (!verifyResp.getResult()) { 38 | return new HttpResponseData<>(StringUtils.EMPTY, verifyResp.getErrorCode(), verifyResp.getErrorMessage()); 39 | } 40 | return new HttpResponseData<>(DataToolUtils.getRandomSalt(), HttpReturnCode.SUCCESS); 41 | } 42 | 43 | @Override 44 | public HttpResponseData fetchData(CredentialPojo authToken, String signedNonce) { 45 | ResponseData verifyResp = credentialPojoService.verify(authToken.getIssuer(), authToken); 46 | if (!verifyResp.getResult()) { 47 | return new HttpResponseData<>(StringUtils.EMPTY, verifyResp.getErrorCode(), verifyResp.getErrorMessage()); 48 | } 49 | // TODO verify signedNonce I: with local storage 50 | // verify signedNonce II: with on-chain toWeId 51 | /* 52 | String toWeId = (String) authToken.getClaim().get("toWeId"); 53 | Sign.SignatureData signatureData = 54 | DataToolUtils.simpleSignatureDeserialization( 55 | DataToolUtils.base64Decode( 56 | signedNonce.getBytes(StandardCharsets.UTF_8) 57 | ) 58 | ); 59 | String credentialIssuer = authToken.getIssuer(); 60 | ResponseData innerResponseData = 61 | weIdService.getWeIdDocument(credentialIssuer); 62 | WeIdDocument weIdDocument = innerResponseData.getResult(); 63 | ErrorCode errorCode = DataToolUtils 64 | .verifySignatureFromWeId(rawData, signatureData, weIdDocument); 65 | if (errorCode.getCode() != ErrorCode.SUCCESS.getCode()) { 66 | return new ResponseData<>(false, errorCode); 67 | } 68 | */ 69 | // verify III: check if serviceUrl exists in this local registered endpoints 70 | String serviceUrl = (String) authToken.getClaim().get("serviceUrl"); 71 | String hostname; 72 | Integer port; 73 | String endpointName; 74 | try { 75 | URI uri = new URI(serviceUrl); 76 | hostname = uri.getHost(); 77 | port = uri.getPort(); 78 | String path = uri.getPath(); 79 | if (StringUtils.isEmpty(hostname) || StringUtils.isEmpty(path) || port < 0) { 80 | logger.error("Service URL illegal: {}", serviceUrl); 81 | return new HttpResponseData<>(StringUtils.EMPTY, HttpReturnCode.INPUT_ILLEGAL); 82 | } 83 | // Truncate the first slash 84 | endpointName = path.substring(1); 85 | } catch (Exception e) { 86 | logger.error("Service URL illegal: {}", serviceUrl); 87 | return new HttpResponseData<>(StringUtils.EMPTY, HttpReturnCode.INPUT_ILLEGAL); 88 | } 89 | String endpointInAddr = hostname + ":" + port.toString(); 90 | logger.debug("The Endpoint to fetch is {} and the endpointName is {}", endpointInAddr, endpointName); 91 | EndpointDataUtil.loadAllEndpointInfoFromProps(); 92 | List allEndpoints = EndpointDataUtil.getAllEndpointInfo(); 93 | boolean found = false; 94 | for (EndpointInfo endpointInfo : allEndpoints) { 95 | logger.debug("Endpoint name to-check is {}", endpointInfo.getRequestName()); 96 | if (endpointName.equalsIgnoreCase(endpointInfo.getRequestName())) { 97 | List inAddrs = endpointInfo.getInAddr(); 98 | for (String inAddr : inAddrs) { 99 | logger.debug("endpoint addr to-check is {}", endpointInAddr); 100 | if (inAddr.equalsIgnoreCase(endpointInAddr)) { 101 | found = true; 102 | break; 103 | } 104 | } 105 | if (found) { 106 | break; 107 | } 108 | } 109 | } 110 | if (!found) { 111 | return new HttpResponseData<>(StringUtils.EMPTY, HttpReturnCode.RPC_ENDPOINT_NOT_EXIST); 112 | } 113 | // Final: invoke endpoint via provided resourceId 114 | EndpointRequest endpointRequest = new EndpointRequest(); 115 | endpointRequest.setRequestName(endpointName); 116 | endpointRequest.setRequestBody((String) authToken.getClaim().get("resourceId")); 117 | 118 | try { 119 | String uuid = RpcConnectionHandler 120 | .send(endpointInAddr, endpointRequest).getRespBody(); 121 | if (StringUtils.isEmpty(uuid)) { 122 | return new HttpResponseData<>(null, HttpReturnCode.RPC_SEND_FAIL); 123 | } 124 | return RpcConnectionHandler.get(uuid); 125 | } catch (Exception e) { 126 | return new HttpResponseData<>(null, HttpReturnCode.RPC_SEND_FAIL.getCode(), 127 | HttpReturnCode.RPC_GET_FAIL.getCodeDesc() + e.getMessage()); 128 | } 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/service/impl/EndpointServiceImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.service.impl; 21 | 22 | import java.util.List; 23 | 24 | import org.apache.commons.lang3.StringUtils; 25 | import org.slf4j.Logger; 26 | import org.slf4j.LoggerFactory; 27 | import org.springframework.stereotype.Component; 28 | 29 | import com.webank.weid.http.constant.HttpReturnCode; 30 | import com.webank.weid.http.protocol.request.EndpointRequest; 31 | import com.webank.weid.http.protocol.response.EndpointInfo; 32 | import com.webank.weid.http.protocol.response.HttpResponseData; 33 | import com.webank.weid.http.service.BaseService; 34 | import com.webank.weid.http.service.EndpointService; 35 | import com.webank.weid.http.service.rpc.RpcConnectionHandler; 36 | import com.webank.weid.http.util.EndpointDataUtil; 37 | 38 | @Component 39 | public class EndpointServiceImpl extends BaseService implements EndpointService { 40 | 41 | static { 42 | RpcConnectionHandler.init(); 43 | } 44 | 45 | /** 46 | * Get all registered endpoints, locally. 47 | * 48 | * @return endpoint info list 49 | */ 50 | public HttpResponseData> getAllEndpoints() { 51 | try { 52 | EndpointDataUtil.loadAllEndpointInfoFromProps(); 53 | return new HttpResponseData<>(EndpointDataUtil.getAllEndpointInfo(), 54 | HttpReturnCode.SUCCESS); 55 | } catch (Exception e) { 56 | return new HttpResponseData<>(null, HttpReturnCode.RPC_FETCH_FAIL.getCode(), 57 | HttpReturnCode.RPC_FETCH_FAIL.getCodeDesc() + e.getMessage()); 58 | } 59 | } 60 | 61 | /** 62 | * Re-route an endpoint service to remote (SDK) machine. Check fisrt to make sure Remote machine 63 | * needs to be able to handle the request. 64 | * 65 | * @param endpointRequest endpoint request - name and body 66 | * @return any String 67 | */ 68 | public HttpResponseData invokeEndpointService(EndpointRequest endpointRequest) { 69 | List endpointInfoList = EndpointDataUtil.getAllEndpointInfo(); 70 | for (EndpointInfo endpointInfo : endpointInfoList) { 71 | String requestName = endpointInfo.getRequestName(); 72 | if (requestName.equalsIgnoreCase(endpointRequest.getRequestName())) { 73 | try { 74 | String uuid = RpcConnectionHandler 75 | .randomSend(endpointInfo.getInAddr(), endpointRequest).getRespBody(); 76 | if (StringUtils.isEmpty(uuid)) { 77 | return new HttpResponseData<>(null, HttpReturnCode.RPC_SEND_FAIL); 78 | } 79 | return RpcConnectionHandler.get(uuid); 80 | } catch (Exception e) { 81 | return new HttpResponseData<>(null, HttpReturnCode.RPC_SEND_FAIL.getCode(), 82 | HttpReturnCode.RPC_GET_FAIL.getCodeDesc() + e.getMessage()); 83 | } 84 | } 85 | } 86 | return new HttpResponseData<>(null, HttpReturnCode.RPC_ENDPOINT_NOT_EXIST.getCode(), 87 | HttpReturnCode.RPC_ENDPOINT_NOT_EXIST.getCodeDesc() + ": " + endpointRequest 88 | .getRequestName()); 89 | } 90 | 91 | /** 92 | * Get an endpoint info, locally. 93 | * 94 | * @param endpointName endpoint name 95 | * @return endpointInfo 96 | */ 97 | public HttpResponseData getEndpoint(String endpointName) { 98 | try { 99 | List endpointInfoList = EndpointDataUtil.getAllEndpointInfo(); 100 | for (EndpointInfo endpointInfo : endpointInfoList) { 101 | if (endpointInfo.getRequestName().equalsIgnoreCase(endpointName)) { 102 | return new HttpResponseData<>(endpointInfo, HttpReturnCode.SUCCESS); 103 | } 104 | } 105 | return new HttpResponseData<>(null, HttpReturnCode.RPC_GET_FAIL); 106 | } catch (Exception e) { 107 | return new HttpResponseData<>(null, HttpReturnCode.RPC_GET_FAIL.getCode(), 108 | HttpReturnCode.RPC_GET_FAIL.getCodeDesc() + e.getMessage()); 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/service/impl/InvokerCptServiceImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.service.impl; 21 | 22 | import com.fasterxml.jackson.databind.JsonNode; 23 | import com.fasterxml.jackson.databind.ObjectMapper; 24 | import com.webank.weid.blockchain.constant.ErrorCode; 25 | import com.webank.weid.blockchain.protocol.response.ResponseData; 26 | import com.webank.weid.constant.ParamKeyConstant; 27 | import com.webank.weid.exception.InitWeb3jException; 28 | import com.webank.weid.exception.LoadContractException; 29 | import com.webank.weid.http.constant.HttpReturnCode; 30 | import com.webank.weid.http.constant.WeIdentityParamKeyConstant; 31 | import com.webank.weid.http.protocol.request.InputArg; 32 | import com.webank.weid.http.protocol.response.HttpResponseData; 33 | import com.webank.weid.http.service.BaseService; 34 | import com.webank.weid.http.service.InvokerCptService; 35 | import com.webank.weid.http.util.JsonUtil; 36 | import com.webank.weid.http.util.KeyUtil; 37 | import com.webank.weid.protocol.base.WeIdAuthentication; 38 | import com.webank.weid.protocol.base.WeIdPrivateKey; 39 | import com.webank.weid.protocol.request.CptStringArgs; 40 | import com.webank.weid.service.impl.CptServiceImpl; 41 | import com.webank.weid.service.rpc.CptService; 42 | import org.apache.commons.lang3.StringUtils; 43 | import org.slf4j.Logger; 44 | import org.slf4j.LoggerFactory; 45 | import org.springframework.stereotype.Component; 46 | 47 | @Component 48 | public class InvokerCptServiceImpl extends BaseService implements InvokerCptService { 49 | 50 | private Logger logger = LoggerFactory.getLogger(InvokerCptService.class); 51 | 52 | private CptService cptService = new CptServiceImpl(); 53 | 54 | //private RawTransactionService rawTransactionService = new RawTransactionServiceImpl(); 55 | 56 | /** 57 | * Register a new CPT to blockchain via Invoke function. 58 | * 59 | * @param registerArgs the args 60 | * @return the resp data 61 | */ 62 | public HttpResponseData registerCptInvoke(InputArg registerArgs) { 63 | try { 64 | JsonNode functionArgNode = new ObjectMapper() 65 | .readTree(registerArgs.getFunctionArg()); 66 | JsonNode weIdNode = functionArgNode.get(ParamKeyConstant.WEID); 67 | JsonNode cptJsonSchemaNode = functionArgNode.get(ParamKeyConstant.CPT_JSON_SCHEMA); 68 | JsonNode txnArgNode = new ObjectMapper() 69 | .readTree(registerArgs.getTransactionArg()); 70 | JsonNode keyIndexNode = txnArgNode.get(WeIdentityParamKeyConstant.KEY_INDEX); 71 | if (weIdNode == null || StringUtils.isEmpty(weIdNode.textValue()) 72 | || cptJsonSchemaNode == null || StringUtils.isEmpty(cptJsonSchemaNode.toString()) 73 | || keyIndexNode == null || StringUtils.isEmpty(keyIndexNode.textValue())) { 74 | return new HttpResponseData<>(null, HttpReturnCode.INPUT_NULL); 75 | } 76 | 77 | String weIdPrivKey = KeyUtil 78 | .getPrivateKeyByWeId(KeyUtil.SDK_PRIVKEY_PATH, keyIndexNode.textValue()); 79 | if (StringUtils.isEmpty(weIdPrivKey)) { 80 | return new HttpResponseData<>(null, HttpReturnCode.INVOKER_ILLEGAL); 81 | } 82 | WeIdAuthentication weIdAuthentication = this.buildWeIdAuthority( 83 | weIdPrivKey, 84 | weIdNode.textValue()); 85 | CptStringArgs cptStringArgs = new CptStringArgs(); 86 | cptStringArgs.setWeIdAuthentication(weIdAuthentication); 87 | cptStringArgs.setCptJsonSchema(cptJsonSchemaNode.toString()); 88 | ResponseData response; 89 | try { 90 | response = cptService.registerCpt(cptStringArgs); 91 | } catch (Exception e) { 92 | logger.error( 93 | "[queryCpt]: unknow error. cptId:{}.", 94 | registerArgs, 95 | e); 96 | return new HttpResponseData<>(null, HttpReturnCode.WEID_SDK_ERROR); 97 | } 98 | return new HttpResponseData<>( 99 | JsonUtil.convertJsonToSortedMap(JsonUtil.objToJsonStr(response.getResult())), 100 | response.getErrorCode(), 101 | response.getErrorMessage()); 102 | } catch (LoadContractException e) { 103 | return new HttpResponseData<>(null, HttpReturnCode.CONTRACT_ERROR.getCode(), HttpReturnCode.CONTRACT_ERROR.getCodeDesc()); 104 | } catch (InitWeb3jException e) { 105 | return new HttpResponseData<>(null, HttpReturnCode.WEB3J_ERROR.getCode(), HttpReturnCode.WEB3J_ERROR.getCodeDesc()); 106 | } catch (Exception e) { 107 | logger.error( 108 | "[queryCpt]: unknow error. cptId:{}.", 109 | registerArgs, 110 | e); 111 | return new HttpResponseData<>(null, HttpReturnCode.UNKNOWN_ERROR.getCode(), 112 | HttpReturnCode.UNKNOWN_ERROR.getCodeDesc().concat(e.getMessage())); 113 | } 114 | } 115 | 116 | /** 117 | * Call to WeID SDK with direct transaction hex String, to register CPT. 118 | * 119 | * @param transactionHex the transactionHex value 120 | * @return String in ResponseData 121 | */ 122 | public HttpResponseData registerCptWithTransactionHex(String transactionHex) { 123 | try { 124 | com.webank.weid.blockchain.protocol.response.ResponseData responseData = rawTransactionService.registerCpt(transactionHex); 125 | if (responseData.getErrorCode() != ErrorCode.SUCCESS.getCode()) { 126 | logger.error("[registerCpt]: error occurred: {}, {}", responseData.getErrorCode(), 127 | responseData.getErrorMessage()); 128 | } 129 | return new HttpResponseData<>(responseData.getResult(), responseData.getErrorCode(), 130 | responseData.getErrorMessage()); 131 | } catch (LoadContractException e) { 132 | return new HttpResponseData<>(null, HttpReturnCode.CONTRACT_ERROR.getCode(), HttpReturnCode.CONTRACT_ERROR.getCodeDesc()); 133 | } catch (InitWeb3jException e) { 134 | return new HttpResponseData<>(null, HttpReturnCode.WEB3J_ERROR.getCode(), HttpReturnCode.WEB3J_ERROR.getCodeDesc()); 135 | } catch (Exception e) { 136 | logger.error("[registerCpt]: unknown error, input arguments:{}", 137 | transactionHex, 138 | e); 139 | return new HttpResponseData<>(StringUtils.EMPTY, 140 | HttpReturnCode.WEID_SDK_ERROR.getCode(), 141 | HttpReturnCode.WEID_SDK_ERROR.getCodeDesc().concat(e.getMessage())); 142 | } 143 | } 144 | 145 | private WeIdAuthentication buildWeIdAuthority(String weIdPrivateKeyStr, String weId) { 146 | 147 | WeIdPrivateKey weIdPrivateKey = new WeIdPrivateKey(); 148 | weIdPrivateKey.setPrivateKey(weIdPrivateKeyStr); 149 | 150 | WeIdAuthentication weIdAuthentication = new WeIdAuthentication(); 151 | weIdAuthentication.setWeId(weId); 152 | weIdAuthentication.setWeIdPrivateKey(weIdPrivateKey); 153 | return weIdAuthentication; 154 | } 155 | 156 | /** 157 | * Query CPT via the InvokeFunction API. 158 | * 159 | * @param queryArgs the query arg 160 | * @return the CPT data 161 | */ 162 | public HttpResponseData queryCptInvoke(InputArg queryArgs) { 163 | try { 164 | JsonNode cptIdNode = new ObjectMapper() 165 | .readTree(queryArgs.getFunctionArg()) 166 | .get(ParamKeyConstant.CPT_ID); 167 | if (cptIdNode == null || StringUtils 168 | .isEmpty(JsonUtil.removeDoubleQuotes(cptIdNode.toString()))) { 169 | return new HttpResponseData<>(null, HttpReturnCode.INPUT_NULL); 170 | } 171 | Integer cptId; 172 | try { 173 | cptId = Integer.valueOf(JsonUtil.removeDoubleQuotes(cptIdNode.toString())); 174 | } catch (Exception e) { 175 | return new HttpResponseData<>(null, HttpReturnCode.VALUE_FORMAT_ILLEGAL); 176 | } 177 | ResponseData response; 178 | try { 179 | response = cptService.queryCpt(cptId); 180 | } catch (Exception e) { 181 | logger.error( 182 | "[queryCpt]: unknow error. cptId:{}.", 183 | queryArgs, 184 | e); 185 | return new HttpResponseData<>(null, HttpReturnCode.WEID_SDK_ERROR); 186 | } 187 | return new HttpResponseData<>( 188 | JsonUtil.convertJsonToSortedMap(JsonUtil.objToJsonStr(response.getResult())), 189 | response.getErrorCode(), 190 | response.getErrorMessage()); 191 | } catch (LoadContractException e) { 192 | return new HttpResponseData<>(null, HttpReturnCode.CONTRACT_ERROR.getCode(), HttpReturnCode.CONTRACT_ERROR.getCodeDesc()); 193 | } catch (InitWeb3jException e) { 194 | return new HttpResponseData<>(null, HttpReturnCode.WEB3J_ERROR.getCode(), HttpReturnCode.WEB3J_ERROR.getCodeDesc()); 195 | } catch (Exception e) { 196 | logger.error( 197 | "[queryCpt]: unknow error. cptId:{}.", 198 | queryArgs, 199 | e); 200 | return new HttpResponseData<>(null, HttpReturnCode.UNKNOWN_ERROR.getCode(), 201 | HttpReturnCode.UNKNOWN_ERROR.getCodeDesc().concat(e.getMessage())); 202 | } 203 | } 204 | 205 | } 206 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/service/rpc/FixedLengthProtocol.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.service.rpc; 21 | 22 | import org.slf4j.Logger; 23 | import org.slf4j.LoggerFactory; 24 | import org.smartboot.socket.Protocol; 25 | import org.smartboot.socket.extension.decoder.FixedLengthFrameDecoder; 26 | import org.smartboot.socket.transport.AioSession; 27 | 28 | import java.nio.ByteBuffer; 29 | 30 | /** 31 | * Modified from smart-socket. 32 | */ 33 | public class FixedLengthProtocol implements Protocol { 34 | 35 | private static final Logger logger = LoggerFactory.getLogger(FixedLengthProtocol.class); 36 | private static final int INT_BYTES = 4;//int类型的字节长度 37 | 38 | @Override 39 | public String decode(ByteBuffer readBuffer, AioSession session) { 40 | if (session.getAttachment() == null 41 | && readBuffer.remaining() < INT_BYTES) {//首次解码不足四字节,无法知晓消息长度 42 | logger.info("SmartSocket 首次解码不足四字节,无法知晓消息长度"); 43 | return null; 44 | } 45 | FixedLengthFrameDecoder fixedLengthFrameDecoder; 46 | if (session.getAttachment() != null) { 47 | fixedLengthFrameDecoder = session.getAttachment(); 48 | } else { 49 | int length = readBuffer.getInt();//获得消息体长度 50 | fixedLengthFrameDecoder = new FixedLengthFrameDecoder(length);//构建指定长度的临时缓冲区 51 | session.setAttachment(fixedLengthFrameDecoder);//缓存临时缓冲区 52 | } 53 | 54 | if (!fixedLengthFrameDecoder.decode(readBuffer)) { 55 | logger.info("SmartSocket 已读取的数据不足length,返回null"); 56 | return null;//已读取的数据不足length,返回null 57 | } 58 | //数据读取完毕 59 | ByteBuffer fullBuffer = fixedLengthFrameDecoder.getBuffer(); 60 | byte[] bytes = new byte[fullBuffer.remaining()]; 61 | fullBuffer.get(bytes); 62 | session.setAttachment(null);//释放临时缓冲区 63 | return new String(bytes); 64 | } 65 | 66 | public static ByteBuffer encode(String msg) { 67 | logger.info("SmartSocket 开始编码"); 68 | byte[] bytes = msg.getBytes(); 69 | ByteBuffer buffer = ByteBuffer.allocate(INT_BYTES + bytes.length); 70 | buffer.putInt(bytes.length);//消息头 71 | buffer.put(bytes);//消息体 72 | buffer.flip(); 73 | return buffer; 74 | } 75 | } -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/service/rpc/RpcClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.service.rpc; 21 | 22 | import com.webank.weid.http.constant.HttpReturnCode; 23 | import com.webank.weid.http.constant.WeIdentityServiceEndpoint; 24 | import com.webank.weid.http.protocol.response.HttpResponseData; 25 | import java.io.IOException; 26 | import java.nio.ByteBuffer; 27 | import java.util.Map; 28 | import java.util.UUID; 29 | import java.util.concurrent.ConcurrentHashMap; 30 | import java.util.concurrent.ExecutionException; 31 | import lombok.Getter; 32 | import lombok.Setter; 33 | import org.apache.commons.lang3.StringUtils; 34 | import org.slf4j.Logger; 35 | import org.slf4j.LoggerFactory; 36 | import org.smartboot.socket.MessageProcessor; 37 | import org.smartboot.socket.StateMachineEnum; 38 | import org.smartboot.socket.transport.AioQuickClient; 39 | import org.smartboot.socket.transport.AioSession; 40 | 41 | 42 | public class RpcClient { 43 | 44 | private static final Logger logger = LoggerFactory.getLogger(RpcClient.class); 45 | 46 | private static final int STATE_PENDING = 0; 47 | private static final int STATE_RECEIVED = 1; 48 | private static final int STATE_TIMEOUT = 2; 49 | private static final int STATE_FAILED = 3; 50 | private static final int POLL_INTERNAL_MILLIS = 500; 51 | private static final int MAX_RETRIES = 20; 52 | 53 | // The results and states per uuid w.r.t session. 54 | private AioSession session = null; 55 | private Map resultMap = new ConcurrentHashMap<>(); 56 | private Map stateMap = new ConcurrentHashMap<>(); 57 | 58 | // The host/port information for this client. 59 | @Getter 60 | @Setter 61 | private String host; 62 | @Getter 63 | @Setter 64 | private int port; 65 | 66 | /** 67 | * Constructor with supplied host and port String. 68 | */ 69 | protected RpcClient(String hostport) throws Exception { 70 | setHostPort(hostport); 71 | session = getNewSession(this.host, this.port); 72 | } 73 | 74 | /** 75 | * Enforce a client re-connect based on pre-set host and port. 76 | */ 77 | protected void reconnect() throws Exception { 78 | if (isValid()) { 79 | session.close(); 80 | } 81 | session = getNewSession(host, port); 82 | } 83 | 84 | /** 85 | * Return the validity of this client. 86 | */ 87 | protected boolean isValid() { 88 | return (session != null) && !session.isInvalid(); 89 | } 90 | 91 | /** 92 | * Send the message to RPC server. 93 | */ 94 | protected HttpResponseData send(String msg) { 95 | String uuid = UUID.randomUUID().toString(); 96 | String message = msg + WeIdentityServiceEndpoint.EPS_SEPARATOR + uuid; 97 | ByteBuffer byteBuffer = FixedLengthProtocol.encode(message); 98 | byte[] resp = new byte[byteBuffer.remaining()]; 99 | byteBuffer.get(resp, 0, resp.length); 100 | resultMap.put(uuid, StringUtils.EMPTY); 101 | stateMap.put(uuid, STATE_PENDING); 102 | try { 103 | session.writeBuffer().write(resp); 104 | session.writeBuffer().flush(); 105 | } catch (IOException e) { 106 | stateMap.put(uuid, STATE_FAILED); 107 | logger.debug("Failed to send message. ", e.getMessage()); 108 | return new HttpResponseData<>(StringUtils.EMPTY, 109 | HttpReturnCode.RPC_SEND_FAIL.getCode(), e.getMessage()); 110 | } 111 | return new HttpResponseData<>(uuid, HttpReturnCode.SUCCESS); 112 | } 113 | 114 | /** 115 | * Periodically fetch the result from the given UUID. 116 | */ 117 | protected HttpResponseData get(String uuid) throws Exception { 118 | for (int i = 0; i < MAX_RETRIES; i++) { 119 | if (stateMap.get(uuid) == STATE_RECEIVED) { 120 | return new HttpResponseData<>(resultMap.get(uuid), HttpReturnCode.SUCCESS); 121 | } 122 | Thread.sleep(POLL_INTERNAL_MILLIS); 123 | } 124 | stateMap.put(uuid, STATE_TIMEOUT); 125 | return new HttpResponseData<>(StringUtils.EMPTY, HttpReturnCode.RPC_FETCH_FAIL); 126 | } 127 | 128 | /** 129 | * Close the RPC connection. Can be re-opened via the reconnect() function. 130 | */ 131 | protected void close() { 132 | session.close(); 133 | } 134 | 135 | private AioSession getNewSession(String host, int port) 136 | throws InterruptedException, ExecutionException, IOException { 137 | AioQuickClient client = new AioQuickClient(host, port, 138 | new FixedLengthProtocol(), new MessageProcessor() { 139 | public void process(AioSession session, String msg) { 140 | String uuid = msg.substring(msg.length() - 36); 141 | resultMap.put(uuid, msg.substring(0, msg.length() - 39)); 142 | stateMap.put(uuid, STATE_RECEIVED); 143 | } 144 | 145 | public void stateEvent(AioSession session, StateMachineEnum stateMachineEnum, 146 | Throwable throwable) { 147 | } 148 | }); 149 | try { 150 | return client.start(); 151 | } catch (Exception e) { 152 | client.shutdownNow(); 153 | logger.debug("Exception occurred during trying to establish RPC Client task: ", e); 154 | return null; 155 | } 156 | } 157 | 158 | protected void setHostPort(String hostPort) { 159 | this.host = StringUtils.splitByWholeSeparator(hostPort, ":")[0]; 160 | this.port = Integer.valueOf(StringUtils.splitByWholeSeparator(hostPort, ":")[1]); 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/service/rpc/SendTester.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.service.rpc; 21 | 22 | import com.webank.weid.http.constant.WeIdentityServiceEndpoint; 23 | import com.webank.weid.http.protocol.request.EndpointRequest; 24 | 25 | public class SendTester { 26 | 27 | public static void main(String[] args) throws Exception { 28 | // Test direct send via client 29 | String hostport = "127.0.1:6095"; 30 | // need boot up server first 31 | RpcClient rpcClient = new RpcClient(hostport); 32 | EndpointRequest endpointRequest = new EndpointRequest(); 33 | endpointRequest.setRequestName(WeIdentityServiceEndpoint.FETCH_FUNCTION); 34 | endpointRequest.setRequestBody("123"); 35 | String uuid = RpcConnectionHandler.send(hostport, endpointRequest).getRespBody(); 36 | String endpointInfoString = RpcConnectionHandler.get(uuid).getRespBody(); 37 | System.out.println(endpointInfoString); 38 | RpcConnectionHandler.init(); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/util/JsonUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.util; 21 | 22 | import com.fasterxml.jackson.annotation.JsonAutoDetect; 23 | import com.fasterxml.jackson.annotation.PropertyAccessor; 24 | import com.fasterxml.jackson.core.JsonProcessingException; 25 | import com.fasterxml.jackson.databind.DeserializationFeature; 26 | import com.fasterxml.jackson.databind.JsonNode; 27 | import com.fasterxml.jackson.databind.MapperFeature; 28 | import com.fasterxml.jackson.databind.ObjectMapper; 29 | import com.fasterxml.jackson.databind.ObjectReader; 30 | import com.fasterxml.jackson.databind.ObjectWriter; 31 | import com.fasterxml.jackson.databind.SerializationFeature; 32 | import com.webank.weid.constant.CredentialConstant; 33 | import com.webank.weid.constant.ParamKeyConstant; 34 | import com.webank.weid.exception.DataTypeCastException; 35 | import com.webank.weid.util.DateUtils; 36 | import java.io.IOException; 37 | import java.util.HashMap; 38 | import java.util.Map; 39 | import java.util.TreeMap; 40 | import org.apache.commons.lang3.StringUtils; 41 | 42 | /** 43 | * Handles all Json related tasks. 44 | * 45 | * @author chaoxinhu 46 | */ 47 | 48 | public class JsonUtil { 49 | 50 | private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); 51 | 52 | private static final ObjectWriter OBJECT_WRITER; 53 | private static final ObjectReader OBJECT_READER; 54 | 55 | static { 56 | // sort by letter 57 | OBJECT_MAPPER.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true); 58 | // when map is serialization, sort by key 59 | OBJECT_MAPPER.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true); 60 | // ignore mismatched fields 61 | OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 62 | // use field for serialize and deSerialize 63 | OBJECT_MAPPER.setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE); 64 | OBJECT_MAPPER.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE); 65 | OBJECT_MAPPER.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); 66 | OBJECT_WRITER = OBJECT_MAPPER.writer().withDefaultPrettyPrinter(); 67 | OBJECT_READER = OBJECT_MAPPER.reader(); 68 | } 69 | 70 | /** 71 | * Json String to Object. 72 | * 73 | * @param obj Object 74 | * @param jsonStr Json String 75 | * @return Object 76 | */ 77 | public static Object jsonStrToObj(Object obj, String jsonStr) { 78 | 79 | try { 80 | return OBJECT_READER.readValue( 81 | OBJECT_MAPPER.getFactory().createParser(jsonStr), 82 | obj.getClass()); 83 | } catch (IOException e) { 84 | throw new DataTypeCastException(e); 85 | } 86 | } 87 | 88 | /** 89 | * Object to Json String. 90 | * 91 | * @param obj Object 92 | * @return String 93 | */ 94 | public static String objToJsonStr(Object obj) { 95 | 96 | try { 97 | return OBJECT_WRITER.writeValueAsString(obj); 98 | } catch (JsonProcessingException e) { 99 | throw new DataTypeCastException(e); 100 | } 101 | } 102 | 103 | /** 104 | * Convert a Map to compact Json output, with keys ordered. Use Jackson JsonNode toString() to ensure key order and compact output. 105 | * 106 | * @param map input map 107 | * @return JsonString 108 | */ 109 | public static String mapToCompactJson(Map map) throws Exception { 110 | ObjectWriter objectWriter = OBJECT_MAPPER.writer(); 111 | return objectWriter.writeValueAsString(map); 112 | } 113 | 114 | /** 115 | * Convert a POJO to Map. 116 | * 117 | * @param object POJO 118 | * @return Map 119 | */ 120 | public static Map objToMap(Object object) throws Exception { 121 | JsonNode jsonNode = OBJECT_MAPPER.readTree(objToJsonStr(object)); 122 | return (HashMap) OBJECT_MAPPER.convertValue(jsonNode, HashMap.class); 123 | } 124 | 125 | /** 126 | * Remove the double quotes. Use this instead of plain JsonNode.textValue() to mitigate possible API body input style mixture (with double quotes 127 | * or not), e.g. "cptId":10 or "cptId":"10". 128 | * 129 | * @param inputValue the input value String 130 | * @return the String 131 | */ 132 | public static String removeDoubleQuotes(String inputValue) { 133 | return inputValue.replace("\"", StringUtils.EMPTY); 134 | } 135 | 136 | /** 137 | * Convert Json String into a sorted map object (keys ordered). 138 | * 139 | * @param looseJson the input json String 140 | * @return the String 141 | */ 142 | public static Map convertJsonToSortedMap(String looseJson) { 143 | try { 144 | Map map = (Map) jsonStrToObj( 145 | new HashMap(), looseJson); 146 | return new TreeMap<>(map); 147 | } catch (Exception e) { 148 | return null; 149 | } 150 | } 151 | 152 | /** 153 | * Format a credential pojo object into a Json format Map by tuning the context and date. 154 | * 155 | * @param originalMap the original credential (in map) 156 | * @return the new map 157 | * @throws Exception date conversion related exceptions 158 | */ 159 | public static Map reformatCredentialPojoToJson(Map originalMap) 160 | throws Exception { 161 | Map credMap = new HashMap<>(originalMap); 162 | 163 | // Convert context into @context 164 | Object context = credMap 165 | .get(CredentialConstant.CREDENTIAL_CONTEXT_PORTABLE_JSON_FIELD); 166 | credMap.remove(CredentialConstant.CREDENTIAL_CONTEXT_PORTABLE_JSON_FIELD); 167 | if (!StringUtils.isEmpty(context.toString())) { 168 | credMap.put(ParamKeyConstant.CONTEXT, context); 169 | } else if (StringUtils.isEmpty(credMap.get(ParamKeyConstant.CONTEXT).toString())) { 170 | credMap 171 | .put(ParamKeyConstant.CONTEXT, 172 | CredentialConstant.DEFAULT_CREDENTIAL_CONTEXT); 173 | } 174 | // Convert dates 175 | String issuanceDate = credMap.get(ParamKeyConstant.ISSUANCE_DATE).toString(); 176 | String expirationDate = credMap.get(ParamKeyConstant.EXPIRATION_DATE).toString(); 177 | credMap.put(ParamKeyConstant.ISSUANCE_DATE, 178 | DateUtils.convertUtcDateToTimeStamp(issuanceDate)); 179 | credMap.put(ParamKeyConstant.EXPIRATION_DATE, 180 | DateUtils.convertUtcDateToTimeStamp(expirationDate)); 181 | return credMap; 182 | } 183 | 184 | 185 | } 186 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/util/KeyUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.util; 21 | 22 | import com.webank.weid.protocol.base.WeIdAuthentication; 23 | import com.webank.weid.protocol.base.WeIdPrivateKey; 24 | import com.webank.weid.util.DataToolUtils; 25 | import com.webank.weid.util.WeIdUtils; 26 | import java.io.File; 27 | import java.io.FileInputStream; 28 | import java.io.FileNotFoundException; 29 | import java.io.FileOutputStream; 30 | import java.io.IOException; 31 | import java.io.OutputStreamWriter; 32 | import java.math.BigInteger; 33 | import java.nio.charset.StandardCharsets; 34 | 35 | import org.apache.commons.io.IOUtils; 36 | import org.apache.commons.lang3.StringUtils; 37 | import org.slf4j.Logger; 38 | import org.slf4j.LoggerFactory; 39 | 40 | import com.webank.weid.http.constant.WeIdentityParamKeyConstant; 41 | 42 | /** 43 | * the util of the private key. 44 | * 45 | * @author afeexian 46 | */ 47 | public class KeyUtil { 48 | 49 | private static final Logger logger = LoggerFactory.getLogger(KeyUtil.class); 50 | 51 | /** 52 | * SDK private key storage path. 53 | */ 54 | public static final String SDK_PRIVKEY_PATH = 55 | PropertiesUtil.getProperty("weid.keys.dir"); 56 | 57 | /** 58 | * SDK private key storage path. 59 | */ 60 | public static final String ADMIN_PRIVKEY_PATH = 61 | PropertiesUtil.getProperty("admin.privKeyPath"); 62 | 63 | /** 64 | * slash. 65 | */ 66 | private static final String SLASH_CHARACTER = "/"; 67 | 68 | /** 69 | * this method stores weId private key information by file and stores private key information by itself in actual scene. 70 | * 71 | * @param path save path 72 | * @param weId the weId 73 | * @param privateKey the private key 74 | * @return returns saved results 75 | */ 76 | public static boolean savePrivateKey(String path, String weId, String privateKey) { 77 | 78 | try { 79 | if (null == weId) { 80 | logger.error("weId is null"); 81 | return false; 82 | } 83 | 84 | // get the third paragraph of weId. 85 | String fileName = weId.substring(weId.lastIndexOf(":") + 1); 86 | 87 | // check whether the path exists or not, then create the path and return. 88 | String checkPath = checkDir(path); 89 | String filePath = checkPath + fileName; 90 | 91 | logger.info("save private key into file, weId={}, filePath={}", weId, filePath); 92 | 93 | // save the private key information as the file name for the third paragraph of weId. 94 | saveFile(filePath, privateKey); 95 | return true; 96 | } catch (Exception e) { 97 | logger.error("savePrivateKey error", e); 98 | } 99 | return false; 100 | } 101 | 102 | /** 103 | * get the private key by weId. 104 | * 105 | * @param path the path 106 | * @param weId the weId 107 | * @return returns the private key 108 | */ 109 | public static String getPrivateKeyByWeId(String path, String weId) { 110 | 111 | if (null == weId) { 112 | logger.error("weId is null"); 113 | return StringUtils.EMPTY; 114 | } 115 | 116 | // get the third paragraph of weId. 117 | String fileName = weId.substring(weId.lastIndexOf(":") + 1); 118 | 119 | // check the default passphrase 120 | String passphrase = PropertiesUtil.getProperty("default.passphrase"); 121 | if (fileName.equalsIgnoreCase(passphrase)) { 122 | fileName = WeIdentityParamKeyConstant.DEFAULT_PRIVATE_KEY_FILE_NAME; 123 | path = ADMIN_PRIVKEY_PATH; 124 | } 125 | 126 | // check whether the path exists or not, then create the path and return. 127 | String checkPath = checkDir(path); 128 | String filePath = checkPath + fileName; 129 | 130 | logger.info("get private key from file, weId={}, filePath={}", weId, filePath); 131 | 132 | // get private key information from a file according to the third paragraph of weId. 133 | String privateKey = getDataByPath(filePath); 134 | return privateKey; 135 | } 136 | 137 | /** 138 | * check the path is exists, create and return the path if it does not exist. 139 | * 140 | * @param path the path 141 | * @return returns the path 142 | */ 143 | public static String checkDir(String path) { 144 | 145 | String checkPath = path; 146 | 147 | // stitching the last slash. 148 | if (!checkPath.endsWith(SLASH_CHARACTER)) { 149 | checkPath = checkPath + SLASH_CHARACTER; 150 | } 151 | 152 | // check the path, create the path when it does not exist. 153 | File checkDir = new File(checkPath); 154 | if (!checkDir.exists()) { 155 | boolean success = checkDir.mkdirs(); 156 | if (!success) { 157 | logger.error("checkDir.mkdirs"); 158 | } 159 | } 160 | return checkPath; 161 | } 162 | 163 | /** 164 | * read data from the file. 165 | * 166 | * @param path the file path 167 | * @return returns the data 168 | */ 169 | public static String getDataByPath(String path) { 170 | 171 | logger.info("get data form [{}]", path); 172 | FileInputStream fis = null; 173 | String str = null; 174 | try { 175 | fis = new FileInputStream(path); 176 | byte[] buff = new byte[fis.available()]; 177 | int size = fis.read(buff); 178 | if (size > 0) { 179 | str = new String(buff, StandardCharsets.UTF_8); 180 | } 181 | } catch (FileNotFoundException e) { 182 | logger.error("the file path is not exists", e); 183 | } catch (IOException e) { 184 | logger.error("getDataByPath error", e); 185 | } finally { 186 | IOUtils.closeQuietly(fis); 187 | } 188 | return str; 189 | } 190 | 191 | /** 192 | * save data in a specified file. 193 | * 194 | * @param filePath save file path 195 | * @param dataStr save data 196 | * @return return the file path 197 | */ 198 | public static String saveFile(String filePath, String dataStr) { 199 | 200 | logger.info("save data in to [{}]", filePath); 201 | OutputStreamWriter ow = null; 202 | FileOutputStream fos = null; 203 | try { 204 | File file = new File(filePath); 205 | fos = new FileOutputStream(file); 206 | ow = new OutputStreamWriter(fos, StandardCharsets.UTF_8); 207 | ow.write(dataStr); 208 | return file.getAbsolutePath(); 209 | } catch (IOException e) { 210 | logger.error("writer file exception", e); 211 | } finally { 212 | IOUtils.closeQuietly(ow); 213 | IOUtils.closeQuietly(fos); 214 | } 215 | return StringUtils.EMPTY; 216 | } 217 | 218 | /** 219 | * Build a default WeIdAuthentication from passed-in private key. 220 | * 221 | * @param privateKey the private key in String 222 | * @return weIdAuthentication 223 | */ 224 | public static WeIdAuthentication buildWeIdAuthenticationFromPrivKey(String privateKey) { 225 | if (StringUtils.isBlank(privateKey) || !isPrivateKeyLengthValid(privateKey)) { 226 | logger.error("Private key format or size illegal."); 227 | return null; 228 | } 229 | String keyWeId = WeIdUtils.getWeIdFromPrivateKey(privateKey); 230 | WeIdAuthentication weIdAuthentication = new WeIdAuthentication(); 231 | weIdAuthentication.setWeId(keyWeId); 232 | weIdAuthentication.setAuthenticationMethodId(keyWeId + "#keys-" + DataToolUtils.publicKeyStrFromPrivate(new BigInteger(privateKey))); 233 | WeIdPrivateKey weIdPrivateKey = new WeIdPrivateKey(); 234 | weIdPrivateKey.setPrivateKey(privateKey); 235 | weIdAuthentication.setWeIdPrivateKey(weIdPrivateKey); 236 | return weIdAuthentication; 237 | } 238 | 239 | public static boolean isPrivateKeyLengthValid(String privateKey) { 240 | if (StringUtils.isBlank(privateKey)) { 241 | return false; 242 | } 243 | WeIdPrivateKey weIdPrivateKey = new WeIdPrivateKey(); 244 | weIdPrivateKey.setPrivateKey(privateKey); 245 | if (WeIdUtils.isPrivateKeyValid(weIdPrivateKey)) { 246 | BigInteger privKeyBig = new BigInteger(privateKey, 10); 247 | BigInteger MAX_PRIVKEY_VALUE = new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 16); 248 | return (privKeyBig.compareTo(MAX_PRIVKEY_VALUE) <= 0); 249 | } 250 | return false; 251 | } 252 | 253 | public static boolean isPubkeyBytesValid(byte[] publicKey) { 254 | return publicKey.length == 64 && publicKey[0] != 0; 255 | } 256 | 257 | public static boolean isSecretKeyValid(byte[] secretKey) { 258 | return secretKey.length == 32 && secretKey[0] != 0; 259 | } 260 | 261 | public static boolean isKeyPairValid(byte[] privateKey, byte[] publicKey) { 262 | return isSecretKeyValid(privateKey) 263 | && isPubkeyBytesValid(publicKey); 264 | } 265 | } 266 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/util/PropertiesUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.util; 21 | 22 | import java.io.IOException; 23 | import java.io.InputStream; 24 | import java.util.Properties; 25 | 26 | import org.apache.commons.io.IOUtils; 27 | import org.slf4j.Logger; 28 | import org.slf4j.LoggerFactory; 29 | 30 | import com.webank.weid.config.ContractConfig; 31 | import com.webank.weid.blockchain.config.FiscoConfig; 32 | 33 | public class PropertiesUtil { 34 | 35 | private static final Logger logger = LoggerFactory.getLogger(PropertiesUtil.class); 36 | 37 | /** 38 | * Properties object. 39 | */ 40 | private static Properties props; 41 | 42 | /** 43 | * configuration file. 44 | */ 45 | private static final String APPLICATION_FILE = "application.properties"; 46 | 47 | static { 48 | loadProps(); 49 | } 50 | 51 | /** 52 | * load configuration file. 53 | */ 54 | private static synchronized void loadProps() { 55 | props = new Properties(); 56 | InputStream resourceAsStream = PropertiesUtil.class.getClassLoader() 57 | .getResourceAsStream(APPLICATION_FILE); 58 | try { 59 | props.load(resourceAsStream); 60 | logger.info("loadProps finish..."); 61 | } catch (IOException e) { 62 | logger.error("loadProps error", e); 63 | } finally { 64 | try { 65 | IOUtils.closeQuietly(resourceAsStream); 66 | } catch (Exception e) { 67 | logger.error("Failed to close stream!"); 68 | } 69 | } 70 | } 71 | 72 | /** 73 | * read the value in the configuration file according to key. 74 | * 75 | * @param key configured key 76 | * @return returns the value of key 77 | */ 78 | public static String getProperty(String key) { 79 | if (null == props) { 80 | loadProps(); 81 | } 82 | return props.getProperty(key); 83 | } 84 | 85 | /** 86 | * read the value in the configuration file according to key, 87 | * returns the default value when it is not available. 88 | * 89 | * @param key configured key 90 | * @param defaultValue default value 91 | * @return returns the value of key 92 | */ 93 | public static String getProperty(String key, String defaultValue) { 94 | if (null == props) { 95 | loadProps(); 96 | } 97 | return props.getProperty(key, defaultValue); 98 | } 99 | 100 | /** 101 | * On-demand build the contract config info. 102 | * 103 | * @return the contractConfig instance 104 | */ 105 | public static ContractConfig buildContractConfig(FiscoConfig fiscoConfig) { 106 | ContractConfig contractConfig = new ContractConfig(); 107 | contractConfig.setWeIdAddress(fiscoConfig.getWeIdAddress()); 108 | contractConfig.setCptAddress(fiscoConfig.getCptAddress()); 109 | contractConfig.setIssuerAddress(fiscoConfig.getIssuerAddress()); 110 | contractConfig.setEvidenceAddress(fiscoConfig.getEvidenceAddress()); 111 | contractConfig.setSpecificIssuerAddress(fiscoConfig.getSpecificIssuerAddress()); 112 | return contractConfig; 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /src/main/java/com/webank/weid/http/util/TransactionEncoderUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.util; 21 | 22 | import com.fasterxml.jackson.databind.JsonNode; 23 | import com.fasterxml.jackson.databind.ObjectMapper; 24 | import com.webank.weid.blockchain.config.FiscoConfig; 25 | import com.webank.weid.http.constant.HttpReturnCode; 26 | import com.webank.weid.http.constant.WeIdentityFunctionNames; 27 | import com.webank.weid.http.constant.WeIdentityParamKeyConstant; 28 | import com.webank.weid.http.protocol.request.InputArg; 29 | import com.webank.weid.http.protocol.response.EncodedTransactionWrapper; 30 | import com.webank.weid.http.protocol.response.HttpResponseData; 31 | import com.webank.weid.protocol.response.ResponseData; 32 | import com.webank.weid.blockchain.service.fisco.BaseServiceFisco; 33 | import com.webank.weid.util.DataToolUtils; 34 | import com.webank.weid.blockchain.util.TransactionUtils; 35 | 36 | import java.io.IOException; 37 | import java.math.BigInteger; 38 | import java.nio.charset.StandardCharsets; 39 | import java.util.Collections; 40 | import java.util.List; 41 | import org.apache.commons.lang3.StringUtils; 42 | import org.slf4j.Logger; 43 | import org.slf4j.LoggerFactory; 44 | 45 | /** 46 | * Handling all tasks related to encoding and sending transactions. 47 | * 48 | * @author chaoxinhu 49 | */ 50 | public class TransactionEncoderUtil { 51 | 52 | private static Logger logger = LoggerFactory.getLogger(TransactionEncoderUtil.class); 53 | 54 | public static boolean isFiscoBcosV1() { 55 | FiscoConfig fiscoConfig = new FiscoConfig(); 56 | fiscoConfig.load(); 57 | if (fiscoConfig.getVersion().startsWith("1")) { 58 | return true; 59 | } 60 | return false; 61 | } 62 | 63 | /** 64 | * Get a random Nonce for a transaction. 65 | * 66 | * @return nonce in BigInt. 67 | */ 68 | public static BigInteger getNonce() { 69 | return TransactionUtils.getNonce(); 70 | } 71 | 72 | 73 | /** 74 | * Get a rawTransaction instance, based on pre-defined parameters. 75 | * 76 | * @param nonce the nonce value 77 | * @param data the data segment 78 | * @param to contract address 79 | */ 80 | /*public static RawTransaction buildRawTransaction(String nonce, String data, String to) { 81 | return RawTransaction.createTransaction( 82 | new BigInteger(nonce), 83 | new BigInteger("99999999999"), 84 | new BigInteger("99999999999"), 85 | getBlockLimit(), 86 | to, 87 | data 88 | ); 89 | }*/ 90 | 91 | 92 | /** 93 | * Extract and build Input arg for all Service APIs. 94 | * 95 | * @param inputJson the inputJson String 96 | * @return An InputArg instance 97 | */ 98 | public static HttpResponseData buildInputArg(String inputJson) { 99 | try { 100 | ObjectMapper objectMapper = new ObjectMapper(); 101 | JsonNode jsonNode = objectMapper.readTree(inputJson); 102 | if (jsonNode == null) { 103 | logger.error("Null input within: {}", inputJson); 104 | return new HttpResponseData<>(null, HttpReturnCode.INPUT_NULL); 105 | } 106 | JsonNode functionNameNode = jsonNode.get(WeIdentityParamKeyConstant.FUNCTION_NAME); 107 | JsonNode versionNode = jsonNode.get(WeIdentityParamKeyConstant.API_VERSION); 108 | if (functionNameNode == null || StringUtils.isEmpty(functionNameNode.textValue())) { 109 | logger.error("Null input within: {}", jsonNode.toString()); 110 | return new HttpResponseData<>(null, HttpReturnCode.FUNCTION_NAME_ILLEGAL); 111 | } 112 | if (versionNode == null || StringUtils.isEmpty(versionNode.textValue())) { 113 | logger.error("Null input within: {}", jsonNode.toString()); 114 | return new HttpResponseData<>(null, HttpReturnCode.VER_ILLEGAL); 115 | } 116 | // Need to use toString() for pure Objects and textValue() for pure String 117 | JsonNode functionArgNode = jsonNode.get(WeIdentityParamKeyConstant.FUNCTION_ARG); 118 | if (functionArgNode == null || StringUtils.isEmpty(functionArgNode.toString())) { 119 | logger.error("Null input within: {}", jsonNode.toString()); 120 | return new HttpResponseData<>(null, HttpReturnCode.FUNCARG_ILLEGAL); 121 | } 122 | JsonNode txnArgNode = jsonNode.get(WeIdentityParamKeyConstant.TRANSACTION_ARG); 123 | if (txnArgNode == null || StringUtils.isEmpty(txnArgNode.toString())) { 124 | logger.error("Null input within: {}", jsonNode.toString()); 125 | return new HttpResponseData<>(null, HttpReturnCode.TXNARG_ILLEGAL); 126 | } 127 | 128 | String functionArg = functionArgNode.toString(); 129 | String txnArg = txnArgNode.toString(); 130 | InputArg inputArg = new InputArg(); 131 | inputArg.setFunctionArg(functionArg); 132 | inputArg.setTransactionArg(txnArg); 133 | inputArg.setFunctionName(functionNameNode.textValue()); 134 | inputArg.setV(versionNode.textValue()); 135 | return new HttpResponseData<>(inputArg, HttpReturnCode.SUCCESS); 136 | } catch (Exception e) { 137 | logger.error("Json Extraction error within: {}", inputJson); 138 | return new HttpResponseData<>(null, HttpReturnCode.UNKNOWN_ERROR.getCode(), 139 | HttpReturnCode.UNKNOWN_ERROR.getCodeDesc().concat(e.getMessage())); 140 | } 141 | } 142 | 143 | /** 144 | * Get a default blocklimit for a transaction. 145 | * 146 | * @return blocklimit in BigInt. 147 | */ 148 | private static BigInteger getBlockLimit() { 149 | try { 150 | return BigInteger.valueOf(BaseServiceFisco.getBlockNumber()); 151 | } catch (IOException e) { 152 | logger.error("get BlockNumber error.", e); 153 | } 154 | return BigInteger.ZERO; 155 | } 156 | 157 | /** 158 | * Get a rawTransaction instance, based on pre-defined parameters and input Function. 159 | * 160 | * @param data the input function instance 161 | * @param nonce the nonce value 162 | * @param to contract address 163 | * @return rawTransaction 164 | */ 165 | /*private static RawTransaction createRawTransactionFromFunction( 166 | String data, 167 | String nonce, 168 | String to) { 169 | return RawTransaction.createTransaction( 170 | new BigInteger(nonce), 171 | new BigInteger("99999999999"), 172 | new BigInteger("99999999999"), 173 | getBlockLimit(), 174 | to, 175 | data 176 | ); 177 | }*/ 178 | 179 | /** 180 | * Get the encoded function byte array from a rawTransaction. 181 | * 182 | * @param rawTransaction the input rawTransaction 183 | * @return rawTransaction 184 | */ 185 | /*private static byte[] encodeRawTransaction(RawTransaction rawTransaction) { 186 | return TransactionEncoder.encode(rawTransaction); 187 | }*/ 188 | 189 | /** 190 | * Get the encoded transaction byte array and rawTransaction into a json String as output. 191 | * 192 | * @param encodedTransaction the encoded transaction byte array (will be converted to Base64) 193 | * @param data the input rawTransaction's data 194 | * @param blockLimit the blockLimit 195 | * @return Json String, a wrapper including both Base64 encodes, and the rawTransaction 196 | */ 197 | public static String getEncodeOutput(byte[] encodedTransaction, String data, BigInteger blockLimit) { 198 | String base64EncodedTransaction = base64Encode(encodedTransaction); 199 | EncodedTransactionWrapper encodedTransactionWrapper = new EncodedTransactionWrapper(); 200 | encodedTransactionWrapper.setEncodedTransaction(base64EncodedTransaction); 201 | encodedTransactionWrapper.setData(data); 202 | encodedTransactionWrapper.setBlockLimit(blockLimit.toString()); 203 | return JsonUtil.objToJsonStr(encodedTransactionWrapper); 204 | } 205 | 206 | /** 207 | * Convert a non-Base64 byte array into a Base64 encoded String. 208 | * 209 | * @param nonBase64ByteArray byte array 210 | * @return Base64 string 211 | */ 212 | private static String base64Encode(byte[] nonBase64ByteArray) { 213 | return new String(DataToolUtils.base64Encode(nonBase64ByteArray), StandardCharsets.UTF_8); 214 | } 215 | } 216 | -------------------------------------------------------------------------------- /src/main/resources/SpringApplicationContext.xml: -------------------------------------------------------------------------------- 1 | 2 | 20 | 21 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /src/main/resources/WeDPR_dynamic_lib/ffi_selective_disclosure.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WeBankBlockchain/WeIdentity-Rest-Service/437042e6a4d3a56e52bb1a45fd52bf54fc870ce9/src/main/resources/WeDPR_dynamic_lib/ffi_selective_disclosure.dll -------------------------------------------------------------------------------- /src/main/resources/WeDPR_dynamic_lib/libeay32md.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WeBankBlockchain/WeIdentity-Rest-Service/437042e6a4d3a56e52bb1a45fd52bf54fc870ce9/src/main/resources/WeDPR_dynamic_lib/libeay32md.dll -------------------------------------------------------------------------------- /src/main/resources/WeDPR_dynamic_lib/libffi_selective_disclosure.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WeBankBlockchain/WeIdentity-Rest-Service/437042e6a4d3a56e52bb1a45fd52bf54fc870ce9/src/main/resources/WeDPR_dynamic_lib/libffi_selective_disclosure.so -------------------------------------------------------------------------------- /src/main/resources/WeDPR_dynamic_lib/ssleay32md.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WeBankBlockchain/WeIdentity-Rest-Service/437042e6a4d3a56e52bb1a45fd52bf54fc870ce9/src/main/resources/WeDPR_dynamic_lib/ssleay32md.dll -------------------------------------------------------------------------------- /src/main/resources/amop/consumer_private_key.p12: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WeBankBlockchain/WeIdentity-Rest-Service/437042e6a4d3a56e52bb1a45fd52bf54fc870ce9/src/main/resources/amop/consumer_private_key.p12 -------------------------------------------------------------------------------- /src/main/resources/amop/consumer_public_key.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEvpEMM5l37k2izwbs+i+T3ydnqVRG7wXq 3 | Cpnn1fEXZa0Vr1NWJ+8bE9UpY2ZdGWkl/uH3j/yWp3L+8LofDv0wug== 4 | -----END PUBLIC KEY----- 5 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # app service port 2 | server.port=6001 3 | server.http.port=6000 4 | 5 | # https 6 | server.ssl.key-store=classpath:tomcat.keystore 7 | # by default this is 123456 8 | server.ssl.key-store-password= 9 | server.ssl.keyStoreType=JKS 10 | server.ssl.keyAlias=tomcat 11 | server.ssl.enabled=false 12 | server.ssl.ciphers=TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,TLS_RSA_WITH_AES_128_CBC_SHA256,TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA256,TLS_RSA_WITH_AES_256_CBC_SHA,SSL_RSA_WITH_RC4_128_SHA 13 | 14 | # log info 15 | logging.config=classpath:log4j2.xml 16 | 17 | # keys info 18 | admin.privKeyPath=./ 19 | default.passphrase=private_key 20 | weid.keys.dir=keys/ 21 | # endpoint-service 22 | fetch.period.seconds=60 23 | server.hostport.list= -------------------------------------------------------------------------------- /src/main/resources/client.keystore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WeBankBlockchain/WeIdentity-Rest-Service/437042e6a4d3a56e52bb1a45fd52bf54fc870ce9/src/main/resources/client.keystore -------------------------------------------------------------------------------- /src/main/resources/cpt.json: -------------------------------------------------------------------------------- 1 | { 2 | "weId": "did:weid:0x1202577890076397e5ca661b37620ff5174f5605", 3 | "cptJsonSchema": { 4 | "title": "cpt", 5 | "description": "this is cpt", 6 | "properties": { 7 | "name": { 8 | "type": "string", 9 | "description": "the name of certificate owner" 10 | }, 11 | "gender": { 12 | "enum": [ 13 | "F", 14 | "M" 15 | ], 16 | "type": "string", 17 | "description": "the gender of certificate owner" 18 | }, 19 | "age": { 20 | "type": "number", 21 | "description": "the age of certificate owner" 22 | } 23 | }, 24 | "required": [ 25 | "name", 26 | "age" 27 | ] 28 | } 29 | } -------------------------------------------------------------------------------- /src/main/resources/endpoint-data.properties: -------------------------------------------------------------------------------- 1 | ep.1.name=create-photo 2 | ep.1.in=127.0.0.1:6090 3 | ep.1.desc=createphoto 4 | 5 | ep.2.name=create-passes 6 | ep.2.in=127.0.0.1:6092 7 | ep.2.desc=fffee -------------------------------------------------------------------------------- /src/main/resources/fisco.properties: -------------------------------------------------------------------------------- 1 | # Fisco-bcos blockchain node related properties 2 | 3 | ####################################################################################################### 4 | # # 5 | # fisco bcos version config # 6 | # # 7 | ####################################################################################################### 8 | # Version 9 | bcos.version=2 10 | 11 | 12 | ####################################################################################################### 13 | # # 14 | # contract address config # 15 | # # 16 | ####################################################################################################### 17 | # contract address 18 | weId.contractaddress= 19 | cpt.contractaddress= 20 | issuer.contractaddress= 21 | evidence.contractaddress= 22 | specificissuer.contractaddress= 23 | 24 | # This variable is used to distinguish the environment. You can use "dev" to set the development environment, 25 | # "stg" to set the test environment, "prd" to set the production environment, 26 | # If you do not set it, the system will use allOrg as the environment by default. 27 | # It is not recommended. Production use default configuration 28 | cns.profile.active=prdabcf 29 | 30 | ####################################################################################################### 31 | # # 32 | # web3sdk connection config # 33 | # # 34 | ####################################################################################################### 35 | # blockchain connection params 36 | web3sdk.timeout=30 37 | web3sdk.core-pool-size=100 38 | web3sdk.max-pool-size=200 39 | web3sdk.queue-capacity=1000 40 | web3sdk.keep-alive-seconds=60 41 | 42 | 43 | ####################################################################################################### 44 | # # 45 | # fisco bcos 2.0 related config # 46 | # # 47 | ####################################################################################################### 48 | # Fisco-Bcos 2.x params, including Group ID and Encrypt Type 49 | group.id=1 50 | 51 | ####################################################################################################### 52 | # # 53 | # fisco bcos node cert related config # 54 | # # 55 | ####################################################################################################### 56 | # Fisco-Bcos sdk SSL encrypt type, 0:ECDSA, 1:SM2 57 | sdk.sm-crypto=0 58 | # fisco-bcos sdk cert path contains[ca.crt,sdk.crt,sdk.key] 59 | # if sdk.sm-crypto is true, contains [gm] directory, and gm dir contains [gmca.crt,gmsdk.crt,gmsdk.key,gmensdk.crt,gmensdk.key] 60 | sdk.cert-path=resources/conf 61 | 62 | # amop public key of pem and private key of p12 configuration 63 | amop.pub-path=resources/conf/amop/consumer_public_key.pem 64 | amop.pri-path=resources/conf/amop/consumer_private_key.p12 65 | amop.p12-password=123456 -------------------------------------------------------------------------------- /src/main/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | logs/ 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /src/main/resources/server.keystore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WeBankBlockchain/WeIdentity-Rest-Service/437042e6a4d3a56e52bb1a45fd52bf54fc870ce9/src/main/resources/server.keystore -------------------------------------------------------------------------------- /src/main/resources/tb.jks: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WeBankBlockchain/WeIdentity-Rest-Service/437042e6a4d3a56e52bb1a45fd52bf54fc870ce9/src/main/resources/tb.jks -------------------------------------------------------------------------------- /src/main/resources/weidentity.properties: -------------------------------------------------------------------------------- 1 | ####################################################################################################### 2 | # # 3 | # application config # 4 | # # 5 | ####################################################################################################### 6 | # Deploy WeIdentity with blockchain or only database 7 | deploy.style=blockchain 8 | # Crypto type, only use for deploy with database, 0 for ECDSA, 1 for SM 9 | crypto.type=0 10 | 11 | # The organization ID for AMOP communication. 12 | blockchain.orgid=org48 13 | 14 | # The Blockchain Type 15 | blockchain.type=FISCO_BCOS 16 | 17 | # The Chain Id 18 | chain.id=101 19 | 20 | # AMOP Config 21 | # Timeout for amop request, default: 5000ms 22 | amop.request.timeout=5000 23 | # The Communication ID for AMOP 24 | amop.id=org44amop 25 | 26 | # Blockchain node info. 27 | nodes=127.0.0.1:21200 28 | 29 | 30 | ####################################################################################################### 31 | # # 32 | # persistence config # 33 | # # 34 | ####################################################################################################### 35 | # Persistence Layer configurations. Do NOT change this if you are not using Persistence Layer features! 36 | #Support the persistence of mysql and redis. You can choose the type of persistence. 37 | persistence_type=mysql 38 | 39 | # MySQL connection config 40 | # Support multiple data source configurations with comma-separated multiple data sources. 41 | datasource.name=datasource1 42 | 43 | # The configuration of each data source is prefixed by the name of the data source. 44 | datasource1.jdbc.url=jdbc:mysql://127.0.0.1:3307/weidafee?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&rewriteBatchedStatements=true&serverTimezone=Asia/Shanghai 45 | datasource1.jdbc.driver=com.mysql.cj.jdbc.Driver 46 | datasource1.jdbc.username=root 47 | datasource1.jdbc.password=***REMOVED*** 48 | datasource1.jdbc.maxActive=50 49 | datasource1.jdbc.initialSize=5 50 | datasource1.jdbc.minIdle=5 51 | datasource1.jdbc.maxIdle=5 52 | datasource1.jdbc.maxWait=10000 53 | datasource1.jdbc.timeBetweenEvictionRunsMillis=600000 54 | datasource1.jdbc.numTestsPerEvictionRun=5 55 | datasource1.jdbc.minEvictableIdleTimeMillis=1800000 56 | 57 | # Redisson config 58 | # If you want to configure redis in cluster mode, enter multiple node addresses separated by commas. 59 | redis.url= 60 | redis.password= 61 | redis_single.database=0 62 | redis_cluster.idle_connection_timeout=10000 63 | redis_cluster.connect_timeout=10000 64 | redis_cluster.timeout=3000 65 | redis_cluster.slave_connection_minimum_idle_size=10 66 | redis_cluster.slave_connection_pool_size=64 67 | redis_cluster.master_connection_minimum_idle_size=10 68 | redis_cluster.master_connection_pool_size=64 69 | 70 | 71 | ####################################################################################################### 72 | # # 73 | # persistence domain config # 74 | # # 75 | ####################################################################################################### 76 | # Domain configuration, which divides colons into two segments, the first segment is the name of the data source, 77 | # the second segment is the name of the table, and if not, the default is the first data source and the default table `sdk_all_data`, 78 | # Multiple domains can be configured at the same time. 79 | # example: 80 | # domain.credential=datasource1:credential_data 81 | # domain.credential.timeout=86400000 82 | # domain.weidDocument=datasource1:weid_document_data 83 | # domain.credential.timeout=86400000 84 | 85 | # the default domain 86 | domain.defaultInfo=datasource1:default_info 87 | domain.defaultInfo.timeout=31556908799941 88 | 89 | # the domain for save encrypt Key 90 | domain.encryptKey=datasource1:encrypt_key_info 91 | domain.encryptKey.timeout=31556908799941 92 | 93 | # 94 | domain.templateSecret=datasource1:template_secret 95 | domain.templateSecret.timeout=31556908799941 96 | 97 | # 98 | domain.masterKey=datasource1:master_secret 99 | 100 | # 101 | domain.credentialSignature=datasource1:credential_signature 102 | 103 | # weid auth info 104 | domain.weIdAuth=datasource1:weid_auth 105 | 106 | # the domain for save resource 107 | domain.resourceInfo=datasource1:resource_info 108 | domain.resourceInfo.timeout=31556908799941 109 | 110 | # tables for running locally 111 | local.weIdDocument=datasource1:table_weid_document 112 | local.cpt=datasource1:table_cpt 113 | local.policy=datasource1:table_policy 114 | local.presentation=datasource1:table_presentation 115 | local.role=datasource1:table_role 116 | local.authorityIssuer=datasource1:table_authority_issuer 117 | local.specificIssuer=datasource1:table_specific_issuer 118 | local.evidence=datasource1:table_evidence 119 | 120 | ####################################################################################################### 121 | # # 122 | # credential related config # 123 | # # 124 | ####################################################################################################### 125 | # You can configure the maximumSize of the default cache module through caffeineCache.maximumSize.xxx. 126 | caffeineCache.maximumSize.SYS_CPT=100 127 | 128 | # Salt length for Proof creation. 129 | salt.length=5 130 | 131 | # Default length of array value in CPT when creating credential based on ZKP. 132 | zkp.cpt.array.length=5 133 | 134 | 135 | ####################################################################################################### 136 | # # 137 | # endpoint Service config # 138 | # # 139 | ####################################################################################################### 140 | # Endpoint Service Integration-side parameters 141 | # Listener port required to be opened for RPC Server, default: 6010 142 | rpc.listener.port=6010 143 | 144 | 145 | ####################################################################################################### 146 | # # 147 | # timestamp Service config # 148 | # # 149 | ####################################################################################################### 150 | # Timestamp Service Parameters 151 | wesign.accessTokenUrl= 152 | wesign.signTicketUrl= 153 | wesign.timestampUrl= 154 | wesign.appId= 155 | wesign.secret= 156 | -------------------------------------------------------------------------------- /src/test/java/com/webank/weid/http/BaseTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weidentity-java-sdk. 5 | * 6 | * weidentity-java-sdk is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weidentity-java-sdk is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weidentity-java-sdk. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http; 21 | 22 | import java.util.HashMap; 23 | import java.util.Map; 24 | 25 | import com.webank.weid.protocol.response.RsvSignature; 26 | import org.junit.After; 27 | import org.junit.Before; 28 | 29 | import com.webank.weid.http.protocol.response.HttpResponseData; 30 | import com.webank.weid.http.util.TransactionEncoderUtilV2; 31 | import com.webank.weid.util.DataToolUtils; 32 | import com.webank.weid.util.HttpClient; 33 | 34 | /** 35 | * @author darwindu 36 | **/ 37 | public abstract class BaseTest { 38 | 39 | @Before 40 | public void init() { 41 | System.out.println("====start testing"); 42 | } 43 | 44 | @After 45 | public void after() { 46 | System.out.println("====ent testing"); 47 | } 48 | 49 | protected static Map buildEncode( 50 | String functionName, 51 | String nonce 52 | ) { 53 | Map arg = new HashMap(); 54 | arg.put("functionName", functionName); 55 | arg.put("v", "1.0"); 56 | 57 | Map tranMap = new HashMap(); 58 | tranMap.put("nonce", nonce); 59 | arg.put("transactionArg", tranMap); 60 | return arg; 61 | } 62 | 63 | protected static Map encode(String apiName, Map param) throws Exception { 64 | String functionName = param.get("functionName").toString(); 65 | System.out.println(functionName + " - param: " + param); 66 | String doPost = HttpClient.doPost("http://127.0.0.1:6001/" + apiName + "/api/encode", param, false); 67 | System.out.println(functionName + " - encode: " + doPost); 68 | return (Map)DataToolUtils.deserialize(doPost, HashMap.class).get("respBody"); 69 | } 70 | 71 | protected static Map buildSend( 72 | String functionName, 73 | String base64SignedMsg, 74 | String data, 75 | String nonce, 76 | String blockLimit 77 | ) { 78 | Map arg = new HashMap(); 79 | arg.put("functionName", functionName); 80 | arg.put("v", "1.0"); 81 | 82 | Map tranMap = new HashMap(); 83 | tranMap.put("nonce", nonce); 84 | tranMap.put("data", data); 85 | tranMap.put("blockLimit", blockLimit); 86 | tranMap.put("signType", 1); 87 | tranMap.put("signedMessage", base64SignedMsg); 88 | arg.put("transactionArg", tranMap); 89 | 90 | Map funcMap = new HashMap(); 91 | arg.put("functionArg", funcMap); 92 | return arg; 93 | } 94 | 95 | protected static HttpResponseData send(String apiName, Map param) throws Exception { 96 | String functionName = param.get("functionName").toString(); 97 | System.out.println(functionName + " - param: " + param); 98 | String doPost = HttpClient.doPost("http://127.0.0.1:6001/" + apiName + "/api/transact", param, false); 99 | System.out.println(functionName + " - transact: " + doPost); 100 | return DataToolUtils.deserialize(doPost, HttpResponseData.class); 101 | } 102 | 103 | protected static String sign( 104 | String privateKey, 105 | Map map 106 | ) throws Exception { 107 | byte[] encodedTransaction = DataToolUtils 108 | .base64Decode(map.get("encodedTransaction").toString().getBytes()); 109 | RsvSignature clientSignedData = DataToolUtils.signToRsvSignature( 110 | encodedTransaction.toString(), privateKey); 111 | String base64SignedMsg = new String( 112 | DataToolUtils.base64Encode( 113 | TransactionEncoderUtilV2.goSignatureSerialization(clientSignedData))); 114 | return base64SignedMsg; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/test/java/com/webank/weid/http/service/CredentialTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.service; 21 | 22 | import com.webank.weid.constant.CredentialConstant.CredentialProofType; 23 | import com.webank.weid.constant.ParamKeyConstant; 24 | import com.webank.weid.http.BaseTest; 25 | import com.webank.weid.http.constant.WeIdentityFunctionNames; 26 | import com.webank.weid.http.constant.WeIdentityParamKeyConstant; 27 | import com.webank.weid.http.protocol.response.HttpResponseData; 28 | import com.webank.weid.http.service.impl.InvokerWeIdServiceImpl; 29 | import com.webank.weid.http.service.impl.TransactionServiceImpl; 30 | import com.webank.weid.http.util.JsonUtil; 31 | import com.webank.weid.http.util.TransactionEncoderUtilV2; 32 | import com.webank.weid.protocol.base.Credential; 33 | import com.webank.weid.protocol.base.CredentialPojo; 34 | import com.webank.weid.protocol.response.CreateWeIdDataResult; 35 | import com.webank.weid.protocol.response.ResponseData; 36 | import com.webank.weid.protocol.response.RsvSignature; 37 | import com.webank.weid.service.rpc.CredentialPojoService; 38 | import com.webank.weid.service.impl.CredentialPojoServiceImpl; 39 | import com.webank.weid.util.DataToolUtils; 40 | import com.webank.weid.util.DateUtils; 41 | import java.math.BigInteger; 42 | import java.nio.charset.StandardCharsets; 43 | import java.util.HashMap; 44 | import java.util.LinkedHashMap; 45 | import java.util.Map; 46 | 47 | import org.junit.Test; 48 | 49 | public class CredentialTest extends BaseTest { 50 | 51 | TransactionService transactionService = new TransactionServiceImpl(); 52 | InvokerWeIdService invokerWeIdService = new InvokerWeIdServiceImpl(); 53 | CredentialPojoService credentialPojoService = new CredentialPojoServiceImpl(); 54 | 55 | @Test 56 | public void TestClientSideCredentialAll() throws Exception { 57 | // test create 58 | Map funcArgMap = new LinkedHashMap<>(); 59 | funcArgMap.put("cptId", "10"); 60 | funcArgMap.put("issuer", "did:weid:0x865f29d2407e91a8be0d5811c6156b6f1c845f41"); 61 | funcArgMap.put("expirationDate", "2042-11-18T21:12:33Z"); 62 | Map claimMap = new LinkedHashMap<>(); 63 | claimMap.put("acc", "10001"); 64 | claimMap.put("name", "ppp"); 65 | funcArgMap.put("claim", claimMap); 66 | Map txnArgMap = new LinkedHashMap<>(); 67 | Map inputParamMap = new LinkedHashMap<>(); 68 | inputParamMap.put(WeIdentityParamKeyConstant.FUNCTION_ARG, funcArgMap); 69 | inputParamMap.put(WeIdentityParamKeyConstant.TRANSACTION_ARG, txnArgMap); 70 | inputParamMap.put(WeIdentityParamKeyConstant.API_VERSION, 71 | WeIdentityParamKeyConstant.DEFAULT_API_VERSION); 72 | inputParamMap.put(WeIdentityParamKeyConstant.FUNCTION_NAME, 73 | WeIdentityFunctionNames.FUNCNAME_CREATE_CREDENTIAL); 74 | HttpResponseData resp1 = 75 | transactionService.invokeFunction(JsonUtil.objToJsonStr(inputParamMap)); 76 | System.out.println("intermediate result: " + JsonUtil.objToJsonStr(resp1)); 77 | 78 | // simulate client side sign 79 | // this result contains both claim and claimhash 80 | Map credMap = (Map) JsonUtil 81 | .jsonStrToObj(new HashMap(), 82 | JsonUtil.mapToCompactJson((Map) resp1.getRespBody())); 83 | System.out.println(credMap); 84 | String claimHash = credMap.get("claimHash").toString(); 85 | credMap.remove("claimHash"); 86 | Map credForSigMap = new HashMap<>(credMap); 87 | credForSigMap.put("claim", claimHash); 88 | credForSigMap.remove("signature"); 89 | //do sign 90 | //String sign = ClientUtil.signCredential(credMap, privateKey); 91 | String sign = "FeB5"; 92 | Map proofMap = new HashMap<>(); 93 | proofMap.put(ParamKeyConstant.PROOF_CREATED, DateUtils.convertUtcDateToTimeStamp( 94 | DateUtils.convertTimestampToUtc(System.currentTimeMillis()))); 95 | proofMap.put(ParamKeyConstant.PROOF_CREATOR, 96 | "did:weid:0x865f29d2407e91a8be0d5811c6156b6f1c845f41"); 97 | proofMap.put(ParamKeyConstant.PROOF_TYPE, CredentialProofType.ECDSA.getTypeName()); 98 | proofMap.put(ParamKeyConstant.CREDENTIAL_SIGNATURE, sign); 99 | credMap.put(ParamKeyConstant.PROOF, proofMap); 100 | String credentialAfterSign = JsonUtil.mapToCompactJson(credMap); 101 | Credential credential = (Credential) JsonUtil 102 | .jsonStrToObj(new Credential(), credentialAfterSign); 103 | System.out.println("after sign: " + JsonUtil.objToJsonStr(credential)); 104 | 105 | //test verify 106 | Map credJsonMap = JsonUtil.objToMap(credential); 107 | inputParamMap = new LinkedHashMap<>(); 108 | inputParamMap.put(WeIdentityParamKeyConstant.FUNCTION_ARG, credJsonMap); 109 | inputParamMap.put(WeIdentityParamKeyConstant.TRANSACTION_ARG, txnArgMap); 110 | inputParamMap.put(WeIdentityParamKeyConstant.API_VERSION, 111 | WeIdentityParamKeyConstant.DEFAULT_API_VERSION); 112 | inputParamMap.put(WeIdentityParamKeyConstant.FUNCTION_NAME, 113 | WeIdentityFunctionNames.FUNCNAME_VERIFY_CREDENTIAL); 114 | HttpResponseData resp3 = 115 | transactionService.invokeFunction(JsonUtil.objToJsonStr(inputParamMap)); 116 | System.out.println(resp3); 117 | } 118 | 119 | @Test 120 | public void TestEncodeCredentialPojoAll() throws Exception { 121 | CreateWeIdDataResult createWeIdDataResult = invokerWeIdService.createWeId().getResult(); 122 | String weId = createWeIdDataResult.getWeId(); 123 | 124 | // test createargs 125 | Map funcArgMap = new LinkedHashMap<>(); 126 | funcArgMap.put("cptId", "2000000"); 127 | funcArgMap.put("issuer", weId); 128 | funcArgMap.put("expirationDate", "2040-04-18T21:12:33Z"); 129 | Map claimMap = new LinkedHashMap<>(); 130 | claimMap.put("acc", "10001"); 131 | claimMap.put("name", "ppp"); 132 | funcArgMap.put("claim", claimMap); 133 | Map txnArgMap = new LinkedHashMap<>(); 134 | Map inputParamMap = new LinkedHashMap<>(); 135 | inputParamMap.put(WeIdentityParamKeyConstant.FUNCTION_ARG, funcArgMap); 136 | inputParamMap.put(WeIdentityParamKeyConstant.TRANSACTION_ARG, txnArgMap); 137 | inputParamMap.put(WeIdentityParamKeyConstant.API_VERSION, 138 | WeIdentityParamKeyConstant.DEFAULT_API_VERSION); 139 | inputParamMap.put(WeIdentityParamKeyConstant.FUNCTION_NAME, 140 | WeIdentityFunctionNames.FUNCNAME_CREATE_CREDENTIALPOJO); 141 | HttpResponseData resp1 = 142 | transactionService.encodeTransaction(JsonUtil.objToJsonStr(inputParamMap)); 143 | System.out.println("intermediate result: " + resp1.getRespBody()); 144 | 145 | // simulate client-sign 146 | Map credMap = (HashMap) resp1.getRespBody(); 147 | Map proofMap = (HashMap) credMap.get("proof"); 148 | String base64EncRawData = (String) proofMap.get("signatureValue"); 149 | System.out.println(base64EncRawData); 150 | String rawData = new String(DataToolUtils.base64Decode(base64EncRawData.getBytes())); 151 | System.out.println(rawData); 152 | RsvSignature sigData = DataToolUtils.signToRsvSignature(rawData, createWeIdDataResult.getUserWeIdPrivateKey().getPrivateKey()); 153 | byte[] signature = DataToolUtils.base64Encode(DataToolUtils.SigBase64Serialization(sigData).getBytes(StandardCharsets.UTF_8)); 154 | proofMap.put("signatureValue", signature.toString()); 155 | credMap.put("proof", proofMap); 156 | CredentialPojo credentialPojo = DataToolUtils 157 | .deserialize(DataToolUtils.mapToCompactJson(credMap), CredentialPojo.class); 158 | ResponseData verifyResp = credentialPojoService.verify(credentialPojo.getIssuer(), 159 | credentialPojo); 160 | System.out.println(verifyResp.getErrorCode()); 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /src/test/java/com/webank/weid/http/service/EnCodeAndTranscatTest.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.service; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import com.webank.weid.util.DataToolUtils; 7 | import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair; 8 | import org.junit.Assert; 9 | import org.junit.Test; 10 | 11 | import com.webank.weid.http.BaseTest; 12 | 13 | public class EnCodeAndTranscatTest extends BaseTest { 14 | 15 | /*@Test 16 | public void testCreateWeId() throws Exception { 17 | CryptoKeyPair createEcKeyPair = DataToolUtils.cryptoSuite.createKeyPair(); 18 | String nonce = String.valueOf(System.currentTimeMillis()); 19 | String functionName = "createWeId"; 20 | Map buildEncode = buildEncode(functionName, nonce); 21 | // build function arg 22 | Map funcMap = new HashMap(); 23 | funcMap.put("publicKey", createEcKeyPair.getHexPublicKey()); 24 | buildEncode.put("functionArg", funcMap); 25 | Map respBodyMap = encode("weid", buildEncode); 26 | String base64SignedMsg = sign(DataToolUtils.hexStr2DecStr(createEcKeyPair.getHexPrivateKey()), respBodyMap); 27 | System.out.println(functionName + " - sign: " + base64SignedMsg); 28 | Map buildSend = buildSend( 29 | functionName, 30 | base64SignedMsg, 31 | respBodyMap.get("data").toString(), 32 | nonce, 33 | respBodyMap.get("blockLimit").toString() 34 | ); 35 | Integer code = send("weid", buildSend).getErrorCode(); 36 | Assert.assertEquals(0, code.intValue()); 37 | }*/ 38 | } 39 | -------------------------------------------------------------------------------- /src/test/java/com/webank/weid/http/service/PrivateKeyTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright© (2019) WeBank Co., Ltd. 3 | * 4 | * This file is part of weid-http-service. 5 | * 6 | * weid-http-service is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Lesser General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * weid-http-service is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public License 17 | * along with weid-http-service. If not, see . 18 | */ 19 | 20 | package com.webank.weid.http.service; 21 | 22 | import org.apache.commons.lang3.StringUtils; 23 | import org.junit.Assert; 24 | import org.junit.Test; 25 | 26 | import com.webank.weid.http.service.impl.InvokerWeIdServiceImpl; 27 | import com.webank.weid.http.util.KeyUtil; 28 | import com.webank.weid.http.util.PropertiesUtil; 29 | import com.webank.weid.protocol.response.CreateWeIdDataResult; 30 | 31 | public class PrivateKeyTest { 32 | 33 | InvokerWeIdService invokerWeIdService = new InvokerWeIdServiceImpl(); 34 | 35 | @Test 36 | public void testKeysAll() { 37 | CreateWeIdDataResult createWeIdDataResult = invokerWeIdService.createWeId().getResult(); 38 | System.out.println(createWeIdDataResult); 39 | String weId = createWeIdDataResult.getWeId(); 40 | String privKey = createWeIdDataResult.getUserWeIdPrivateKey().getPrivateKey(); 41 | 42 | // test save 43 | KeyUtil.savePrivateKey(KeyUtil.SDK_PRIVKEY_PATH, weId, privKey); 44 | 45 | // test load 46 | String extractedKey = KeyUtil 47 | .getPrivateKeyByWeId(KeyUtil.SDK_PRIVKEY_PATH, weId); 48 | System.out.println(extractedKey); 49 | Assert.assertTrue(StringUtils.equals(extractedKey, privKey)); 50 | 51 | // test load sdk 52 | String extractedKey2 = KeyUtil 53 | .getPrivateKeyByWeId(KeyUtil.SDK_PRIVKEY_PATH, 54 | PropertiesUtil.getProperty("default.passphrase")); 55 | System.out.println(extractedKey2); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/test/java/com/webank/weid/http/service/PropertiesTest.java: -------------------------------------------------------------------------------- 1 | package com.webank.weid.http.service; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import org.junit.Assert; 7 | import org.junit.Test; 8 | 9 | import com.webank.weid.http.protocol.response.EndpointInfo; 10 | import com.webank.weid.http.util.EndpointDataUtil; 11 | 12 | public class PropertiesTest { 13 | 14 | @Test 15 | public void testEndpointDataAll() throws Exception { 16 | List endpointInfoList = EndpointDataUtil.getAllEndpointInfo(); 17 | for (EndpointInfo endpointInfo : endpointInfoList) { 18 | System.out.println(endpointInfo.toString()); 19 | } 20 | EndpointInfo newInfo = new EndpointInfo(); 21 | newInfo.setRequestName("remove-file"); 22 | List result = new ArrayList<>(); 23 | result.add("127.0.3"); 24 | newInfo.setInAddr(result); 25 | newInfo.setDescription("temp"); 26 | EndpointDataUtil.mergeToCentral(newInfo); 27 | newInfo = new EndpointInfo(); 28 | newInfo.setRequestName("remove-file"); 29 | result = new ArrayList<>(); 30 | result.add("127.0.3"); 31 | result.add("127.0.4"); 32 | newInfo.setInAddr(result); 33 | newInfo.setDescription("temp"); 34 | EndpointDataUtil.mergeToCentral(newInfo); 35 | EndpointDataUtil.saveEndpointsToFile(); 36 | endpointInfoList = EndpointDataUtil.getAllEndpointInfo(); 37 | for (EndpointInfo endpointInfo : endpointInfoList) { 38 | System.out.println(endpointInfo.toString()); 39 | } 40 | Assert.assertTrue(EndpointDataUtil.removeEndpoint(newInfo)); 41 | endpointInfoList = EndpointDataUtil.getAllEndpointInfo(); 42 | for (EndpointInfo endpointInfo : endpointInfoList) { 43 | System.out.println(endpointInfo.toString()); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/test/resources/SpringApplicationContext.xml: -------------------------------------------------------------------------------- 1 | 2 | 20 | 21 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /src/test/resources/client.keystore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WeBankBlockchain/WeIdentity-Rest-Service/437042e6a4d3a56e52bb1a45fd52bf54fc870ce9/src/test/resources/client.keystore -------------------------------------------------------------------------------- /src/test/resources/cpt.json: -------------------------------------------------------------------------------- 1 | { 2 | "weId": "did:weid:0x1202577890076397e5ca661b37620ff5174f5605", 3 | "cptJsonSchema": { 4 | "title": "cpt", 5 | "description": "this is cpt", 6 | "properties": { 7 | "name": { 8 | "type": "string", 9 | "description": "the name of certificate owner" 10 | }, 11 | "gender": { 12 | "enum": [ 13 | "F", 14 | "M" 15 | ], 16 | "type": "string", 17 | "description": "the gender of certificate owner" 18 | }, 19 | "age": { 20 | "type": "number", 21 | "description": "the age of certificate owner" 22 | } 23 | }, 24 | "required": [ 25 | "name", 26 | "age" 27 | ] 28 | } 29 | } -------------------------------------------------------------------------------- /src/test/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | /data/app/logs/weid-http-service/ 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /src/test/resources/server.keystore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WeBankBlockchain/WeIdentity-Rest-Service/437042e6a4d3a56e52bb1a45fd52bf54fc870ce9/src/test/resources/server.keystore -------------------------------------------------------------------------------- /src/test/resources/tb.jks: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WeBankBlockchain/WeIdentity-Rest-Service/437042e6a4d3a56e52bb1a45fd52bf54fc870ce9/src/test/resources/tb.jks -------------------------------------------------------------------------------- /weidentity.properties: -------------------------------------------------------------------------------- 1 | ####################################################################################################### 2 | # # 3 | # application config # 4 | # # 5 | ####################################################################################################### 6 | # Deploy WeIdentity with blockchain or only database 7 | deploy.style=database 8 | # Crypto type, only use for deploy with database, 0 for ECDSA, 1 for SM 9 | crypto.type=0 10 | 11 | # The organization ID for AMOP communication. 12 | blockchain.orgid=org48 13 | 14 | # The Blockchain Type 15 | blockchain.type=FISCO_BCOS 16 | 17 | # The Chain Id 18 | chain.id=101 19 | 20 | # AMOP Config 21 | # Timeout for amop request, default: 5000ms 22 | amop.request.timeout=5000 23 | # The Communication ID for AMOP 24 | amop.id=org44amop 25 | 26 | # Blockchain node info. 27 | nodes=127.0.0.1:21200 28 | 29 | 30 | ####################################################################################################### 31 | # # 32 | # persistence config # 33 | # # 34 | ####################################################################################################### 35 | # Persistence Layer configurations. Do NOT change this if you are not using Persistence Layer features! 36 | #Support the persistence of mysql and redis. You can choose the type of persistence. 37 | persistence_type=mysql 38 | 39 | # MySQL connection config 40 | # Support multiple data source configurations with comma-separated multiple data sources. 41 | datasource.name=datasource1 42 | 43 | # The configuration of each data source is prefixed by the name of the data source. 44 | datasource1.jdbc.url=jdbc:mysql://127.0.0.1:3307/weidafee?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&rewriteBatchedStatements=true&serverTimezone=Asia/Shanghai 45 | datasource1.jdbc.driver=com.mysql.cj.jdbc.Driver 46 | datasource1.jdbc.username=root 47 | datasource1.jdbc.password=***REMOVED*** 48 | datasource1.jdbc.maxActive=50 49 | datasource1.jdbc.initialSize=5 50 | datasource1.jdbc.minIdle=5 51 | datasource1.jdbc.maxIdle=5 52 | datasource1.jdbc.maxWait=10000 53 | datasource1.jdbc.timeBetweenEvictionRunsMillis=600000 54 | datasource1.jdbc.numTestsPerEvictionRun=5 55 | datasource1.jdbc.minEvictableIdleTimeMillis=1800000 56 | 57 | # Redisson config 58 | # If you want to configure redis in cluster mode, enter multiple node addresses separated by commas. 59 | redis.url= 60 | redis.password= 61 | redis_single.database=0 62 | redis_cluster.idle_connection_timeout=10000 63 | redis_cluster.connect_timeout=10000 64 | redis_cluster.timeout=3000 65 | redis_cluster.slave_connection_minimum_idle_size=10 66 | redis_cluster.slave_connection_pool_size=64 67 | redis_cluster.master_connection_minimum_idle_size=10 68 | redis_cluster.master_connection_pool_size=64 69 | 70 | 71 | ####################################################################################################### 72 | # # 73 | # persistence domain config # 74 | # # 75 | ####################################################################################################### 76 | # Domain configuration, which divides colons into two segments, the first segment is the name of the data source, 77 | # the second segment is the name of the table, and if not, the default is the first data source and the default table `sdk_all_data`, 78 | # Multiple domains can be configured at the same time. 79 | # example: 80 | # domain.credential=datasource1:credential_data 81 | # domain.credential.timeout=86400000 82 | # domain.weidDocument=datasource1:weid_document_data 83 | # domain.credential.timeout=86400000 84 | 85 | # the default domain 86 | domain.defaultInfo=datasource1:default_info 87 | domain.defaultInfo.timeout=31556908799941 88 | 89 | # the domain for save encrypt Key 90 | domain.encryptKey=datasource1:encrypt_key_info 91 | domain.encryptKey.timeout=31556908799941 92 | 93 | # 94 | domain.templateSecret=datasource1:template_secret 95 | domain.templateSecret.timeout=31556908799941 96 | 97 | # 98 | domain.masterKey=datasource1:master_secret 99 | 100 | # 101 | domain.credentialSignature=datasource1:credential_signature 102 | 103 | # weid auth info 104 | domain.weIdAuth=datasource1:weid_auth 105 | 106 | # the domain for save resource 107 | domain.resourceInfo=datasource1:resource_info 108 | domain.resourceInfo.timeout=31556908799941 109 | 110 | # tables for running locally 111 | local.weIdDocument=datasource1:table_weid_document 112 | local.cpt=datasource1:table_cpt 113 | local.policy=datasource1:table_policy 114 | local.presentation=datasource1:table_presentation 115 | local.role=datasource1:table_role 116 | local.authorityIssuer=datasource1:table_authority_issuer 117 | local.specificIssuer=datasource1:table_specific_issuer 118 | local.evidence=datasource1:table_evidence 119 | 120 | ####################################################################################################### 121 | # # 122 | # credential related config # 123 | # # 124 | ####################################################################################################### 125 | # You can configure the maximumSize of the default cache module through caffeineCache.maximumSize.xxx. 126 | caffeineCache.maximumSize.SYS_CPT=100 127 | 128 | # Salt length for Proof creation. 129 | salt.length=5 130 | 131 | # Default length of array value in CPT when creating credential based on ZKP. 132 | zkp.cpt.array.length=5 133 | 134 | 135 | ####################################################################################################### 136 | # # 137 | # endpoint Service config # 138 | # # 139 | ####################################################################################################### 140 | # Endpoint Service Integration-side parameters 141 | # Listener port required to be opened for RPC Server, default: 6010 142 | rpc.listener.port=6010 143 | 144 | 145 | ####################################################################################################### 146 | # # 147 | # timestamp Service config # 148 | # # 149 | ####################################################################################################### 150 | # Timestamp Service Parameters 151 | wesign.accessTokenUrl= 152 | wesign.signTicketUrl= 153 | wesign.timestampUrl= 154 | wesign.appId= 155 | wesign.secret= 156 | --------------------------------------------------------------------------------